Tuesday, July 20, 2010

Creating Log4J Custom PatternLayout

Suppose we need to add a username information into our logging, with Log4J this can be implemented easily. Log4J allows us to create our own PatternLayout.

PatternLayout has a method createPatternParser() that will basically delegate the task to PatternParser. Here, we can create our own MyPatternLayout by extending it from PatternLayout and delegating the task to our own PatternParser as shown below.

MyPatternLayout.java
package myproject;

import org.apache.log4j.PatternLayout; 
import org.apache.log4j.helpers.PatternParser;

public class MyPatternLayout extends PatternLayout {

    @Override 
    protected PatternParser createPatternParser(String pattern) { 
        return new MyPatternParser(pattern); 
    } 
} 

Since we normally just want to add a new character in the pattern instead of redefining all the characters, we need to make sure that we call super.finalizeConverter(c) as shown below.

PatternParser.java
package myproject;

import org.apache.log4j.helpers.PatternParser;

public class MyPatternParser extends PatternParser { 
    private static final char USERNAME_CHAR = 'u'; 
    
    public MyPatternParser(String pattern) { 
        super(pattern); 
    } 
    
    @Override 
    protected void finalizeConverter(char c) { 
        switch (c) { 
        case USERNAME_CHAR: 
            currentLiteral.setLength(0); 
            addConverter(new MyPatternConverter()); 
            break; 
        default: 
            super.finalizeConverter(c); 
        } 
    } 
} 

MyPatternConverter.java
package myproject;

import org.apache.log4j.helpers.PatternConverter; 
import org.apache.log4j.spi.LoggingEvent;

public class MyPatternConverter extends PatternConverter {

    @Override 
    protected String convert(LoggingEvent evt) { 
        // For simplicity, assume this information is retrieved from somewhere. 
        return "User1"; 
    } 
} 

Main.java
package myproject;

import org.apache.log4j.Logger;

public class Main {

    private static final Logger logger = Logger.getLogger(Main.class); 
    
    public static void main(String[] args) { 
        logger.info("Hello World"); 
        logger.debug("Hello World"); 
        logger.warn("Hello World"); 
        logger.error("Hello World"); 
    } 
} 


Make sure to change the layout to our own custom PatternLayout in the log4j.properties.
log4j.properties
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=myproject.MyPatternLayout 
log4j.appender.A1.layout.ConversionPattern=[%-5p] <%u> [%c.%t] - %m%n

4 comments:

  1. excellent post thanks.
    one way to get the username info is to use the setProperty and getProperty in the LoggingEvent class.

    ReplyDelete
  2. This doesnt seem to work with log4j.xml configuration. It doesn't like the <>

    ReplyDelete