Tuesday, 23 June 2015

How to Create a Custom Appender in log4j2?


In log4j2, you would create a plugin for create custom appender in log4j2.
When you annotate your custom Appender class with @Plugin(name=”MyCustomAppender”, category=”core” elementType=”appender” ,printObject=true) the plugin name becomes the configuration element name, so a configuration with your custom appender would then look like this:


Log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" packages="com.madhu.appender">
    <Appenders>
        <MyCustomAppender name="myapp" >
       <PatternLayout pattern="serial no: %sn |  Date: %d |  level:%level | class name:%logger | method name:%M() |  line number:%L |  Location: %l | message:%m%n" />
        </MyCustomAppender>
    </Appenders>
       <Loggers>
              <Root level="all" additivity="false">
                     <AppenderRef ref="myapp" />

              </Root>
       </Loggers>
</Configuration>

In log4j2.xml file don’t forgot packages attribute here configure your custom appender package.
Now we are create plugin for appender.

MyCustomImpl.java


@Plugin(name="MyCustomAppender", category="Core", elementType="appender", printObject=true)

public class MyCustomImpl extends AbstractAppender {

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();

    protected MyCustomImpl(String name, Filter filter,
            Layout<? extends Serializable> layout, final boolean ignoreExceptions) {
        super(name, filter, layout, ignoreExceptions);
    }
    @PluginFactory
    public static MyCustomImpl createAppender(
            @PluginAttribute("name") String name,
            @PluginElement("Layout") Layout<? extends Serializable> layout,
            @PluginElement("Filter") final Filter filter,
            @PluginAttribute("otherAttribute") String otherAttribute) {
        if (name == null) {
            LOGGER.error("No name provided for MyCustomAppenderImp");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new MyCustomImpl(name, filter, layout, true);

}
       @Override
       public void append(LogEvent event) {
                readLock.lock();
               try {    
                   final byte[] bytes = getLayout().toByteArray(event);
// here I am printing logs into console
                   System.out.println("LOG: " +new String(bytes, "UTF-8"));
               } catch (Exception ex) {
                   if (!ignoreExceptions()) {
                       throw new AppenderLoggingException(ex);
                   }
               } finally {
                   readLock.unlock();
               }
       }
}

Now we can test our custom appender. For this we can write one test class.

Note: Here custom appender plugin name and configuration appender name is same otherwise its won’t work.

Test.java


public class Test {
       public static final Logger LOGGER=LogManager.getLogger(Test.class);
public static void main(String[] args) throws IOException {
       LOGGER.info("this is info message");
       LOGGER.warn("this is warning message");
      
}
}

The output comes like below.

LOG: serial no: 1 |  Date: 2015-06-23 15:32:56,069 |  level:INFO | class name:com.madhu.appender.Test | method name:main() |  line number:15 |  Location: com.madhu.appender.Test.main(Test.java:15) | message:this is info message

LOG: serial no: 2 |  Date: 2015-06-23 15:32:56,072 |  level:WARN | class name:com.madhu.appender.Test | method name:main() |  line number:16 |  Location: com.madhu.appender.Test.main(Test.java:16) | message:this is warning message










5 comments:

  1. Appreciate your time in writing up a very useful blog!!

    ReplyDelete
  2. how to print logs into log file using above example

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi... In Spring 2.x, the constructor AbstractAppender(String, Filter, Layout) is deprecated. So we cannot use super() call here. Can you please help on this one?

    ReplyDelete