Buscar este blog

miércoles, 30 de diciembre de 2015

Log4j 1.x - Custom ThrowableRenderer

With log4j 1.x you can customize the format of your message logs with EnhancedPatternLayout,
There is a special Conversion Character to customize exception traces called throwable. But if you need more control about how to print exceptions you can hook your own renderer.

Create a class which implements org.apache.log4j.spi.ThrowableRenderer.
package es.cixtec.complexarchetype.web.log4j;

import org.apache.log4j.spi.ThrowableRenderer;

public class MyCustomThrowableRenderer implements ThrowableRenderer {

    @Override
    public String[] doRender(final Throwable t) {
        // do something with t
        return new String[] { "This", "is", "a", "custom", "trace" };
    }
}

Then, in log4j.xml, you need to link this class by using the throwableRenderer tag.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"  xmlns:log4j='http://jakarta.apache.org/log4j/'>
    
    <throwableRenderer class="es.sisifo.test.web.log4j.MyCustomThrowableRenderer"/>
    
    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.EnhancedPatternLayout">
        <param name="ConversionPattern" 
          value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>
    
    <appender name="LOG" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${jboss.server.log.dir}/test-web.log" />
        <param name="DatePattern" value="'.'yyyy-MM-dd"/>
        <layout class="org.apache.log4j.EnhancedPatternLayout">
            <param name="ConversionPattern" value="[%-5p][%d{ISO8601}][%-4L] %F>%m%n" />
        </layout>
    </appender>
    

    <root>
        <level value="DEBUG" />
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="LOG" />
    </root>

</log4j:configuration>

As result, when a exception is logged you get something like this.
LOGGER.error("Exceptions happens", new NullPointerException());

[ERROR][2015-12-30 11:33:09,003][45  ] GridServiceImpl.java>Exceptions happens
This
is
a
custom
trace

No hay comentarios:

Publicar un comentario