Use Log4j ObjectRenderer To Log Java Object

Log is an essential feature for each java application, and log4j is one of many uses. Generally we use below java code to log a String value.logger.info("Hello World"); it will output “Hello World” in the appender destination.

But how about to log a java object like this logger.info(new LogJavaObjectInfo());. Generally it will output data like INFO [main] (LogJavaObjectInfo.java:18) - [email protected]
This is not human readable and friendly. To resolve this issue, we have below solutions.

1. Create a Java Class Implement org.apache.log4j.or.ObjectRenderer Interface.
  1. com.dev2qa.java.basic.log4jexample.LogJavaObjectInfoRenderer
    You should override doRender(Object obj) mtehod to return customize String value when log obj (This renderer decorated java object).

    public class LogJavaObjectInfoRenderer implements ObjectRenderer {
    
    	@Override
    	public String doRender(Object obj) {
    		// Convert the obj parameter to LogJavaObjectInfo class object.
    		LogJavaObjectInfo logJavaObjectInfo = (LogJavaObjectInfo)obj;
    		
    		// Invoke the converted object's method.
    		String ret = logJavaObjectInfo.getUserName() + " : " + logJavaObjectInfo.getMessage();
    		
    		return ret;
    	}
    
    }
    
  2. Set The Renderer Class in Eclipse Java Project resources / log4j.properties File. Please see below first line configuration.
    # This means when log LogJavaObjectInfo object, use LogJavaObjectInfoRenderer to output String data.
    log4j.renderer.com.dev2qa.java.basic.log4jexample.LogJavaObjectInfo=com.dev2qa.java.basic.log4jexample.LogJavaObjectInfoRenderer
    
    # Define root logger, logger level is INFO, appender name is appender1
    log4j.rootLogger = INFO, appender1
    
    # Set appender1 to be a Console appender which will print log data to console.
    log4j.appender.appender1=org.apache.log4j.ConsoleAppender
    
    # Define appender1's layout
    log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
    log4j.appender.appender1.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
    

    add log4j.properties file in java project resources folder

  3. Log LogJavaObjectInfo Object In Below Java Code.
    com.dev2qa.java.basic.log4jexample.LogJavaObjectInfo

    public class LogJavaObjectInfo{
    	
    	private String userName;
    	
    	private String message;
    	
    
    	public static void main(String[] args) {
    		
    		// Get root logger.
    		Logger logger = Logger.getRootLogger();
    		
    		// Create a new object.
    		LogJavaObjectInfo logJavaObjectInfo = new LogJavaObjectInfo();
    		
    		// Set object's properties.
    		logJavaObjectInfo.setUserName("Jerry");
    		logJavaObjectInfo.setMessage("Welcome to dev2qa.com");
    		
    		// Log the object use root logger.
    		logger.info(logJavaObjectInfo);
    	}
    
    
    	public String getUserName() {
    		return userName;
    	}
    
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    
    	public String getMessage() {
    		return message;
    	}
    
    
    	public void setMessage(String message) {
    		this.message = message;
    	}
    
    }
    

    log4j objectrenderer java class tree

  4. Run Above Code Get Below Output.This is user friendly enough and human readable.INFO [main] (LogJavaObjectInfo.java:25) - Jerry : Welcome to dev2qa.com
2. Override LogJavaObjectInfo toString() Method.
	@Override
	public String toString() {
		StringBuffer retBuf = new StringBuffer();
		retBuf.append("This message is generated from toString() method. ");
		retBuf.append(this.getUserName());
		retBuf.append(" : ");
		retBuf.append(this.getMessage());
		return retBuf.toString();
	}
	

Now you can remove object renderer configuration in log4j.properties file and run LogJavaObjectInfo main method again, you can get below output.

INFO [main] (LogJavaObjectInfo.java:25) - This message is generated from toString() method. Jerry : Welcome to dev2qa.com

Download “UseLog4jObjectRendererToCustomizeJavaObjectLogInfo.zip” UseLog4jObjectRendererToCustomizeJavaObjectLogInfo.zip – Downloaded 55 times – 2 KB

(Visited 403 times, 3 visits today)
READ :   Spring Boot Integrates slf4j and logback

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.