Search code examples
javalog4j

Is it possible to prefix every line of a stacktrace in log4j?


when you write

logger.error("message", exception);

log4j produces the message and the complete stack trace :

Aug  9 06:26:13 10.175.60.14 myPrefix: [error] [TP-Processor114] [my.class.Name] message : exception
at fatherOfException
at fatherof_fatherOfException
at fatherof_fatherof_fatherOfException
...

my conversion pattern is

log4j.appender.syslog.layout.ConversionPattern=myPrefix: [%p] [%t] [%c] [%x] - %m%n

So, is it possible to prefix every line with myPrefix, as :

    Aug  9 06:26:13 10.175.60.14 myPrefix: [error] [TP-Processor114] [my.class.Name] message : exception
myPrefix    at fatherOfException
myPrefix    at fatherof_fatherOfException
myPrefix    at fatherof_fatherof_fatherOfException
    ...

When I grep my logs on myPrefix, i don't see the stack trace. We have many different prefixes (one per module)

Thanks in advance.


Solution

  • Subclass ThrowableRenderer, for example:

    import org.apache.log4j.DefaultThrowableRenderer;
    import org.apache.log4j.spi.ThrowableRenderer;
    
    public class LogThrowableRenderer implements ThrowableRenderer {
    
        DefaultThrowableRenderer def = new DefaultThrowableRenderer();
    
        @Override
        public String[] doRender(Throwable t) {
            String[] temp = def.doRender(t);
            for (int i = 0; i < temp.length; i++) {
                temp[i] = "myPrefix "+temp[i];
            }
            return temp;
        }
    
    }
    

    Add to your log4j.properties:

    log4j.throwableRenderer=whatever.package.LogThrowableRenderer
    

    This uses the existing DefaultThrowableRenderer to render the stacktrace in the familiar way before adding the prefix, so it will include the Throwable class, message, and cause.