Log4j multiple pattern layout

5.8k Views Asked by At

I'm pretty new with log4j. I want to display log messages with these infos: log timestamp, priority, fully qualified class name, the message, class name only. I try to display twice the CATEGORY, once with a ConversionPattern, and once with an other ConversionPattern. Here is the piece of my log4j.properties:

log4j.appender.JDBC2.layoutPartsDelimiter=#-#    
log4j.appender.B1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n #-#%-4r [%t] %-5p %c{1} %x %m%n

Sadly it does not work. How can I show full qualified class name and class name only in the same log message? TIA.

Francesco

2

There are 2 best solutions below

0
On BEST ANSWER

It was my mistake. As you can see in my precedent post, Delimiter and PatternLayout refer to different appenders. I change

log4j.appender.JDBC2.layoutPartsDelimiter=#-#    
log4j.appender.B1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n #-#%-4r [%t] %-5p %c{1} %x %m%n

into this:

log4j.appender.B1.layoutPartsDelimiter=#-#    
log4j.appender.B1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n #-#%-4r [%t] %-5p %c{1} %x %m%n

and everything works fine, when I use @LAYOUT:1@ I got the first ConversionPattern (left of delimiter #-#). When I use @LAYOUT:2@ I got the second pattern. Thank you.

Francesco

0
On
  1. log4j.appender.B1.layout.ConversionPattern is a key here and you can associate it with only one value. So, if you write like this:

    
    Log4j.appender.B1.layout.ConversionPattern=%some%value%here
    Log4j.appender.B1.layout.ConversionPattern=%another%value%here
    
    The later value would just override the previous one

  2. You can define two different appenders and associate them with the logger you want(the rootLogger as an example):

    
    log4j.rootLogger=debug,console,console2
    
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.target=System.err
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern= %p %C (%F:%M(%L)) -
    %m%n
    
    log4j.appender.console2=org.apache.log4j.ConsoleAppender
    log4j.appender.console2.target=System.err
    log4j.appender.console2.layout=org.apache.log4j.PatternLayout
    log4j.appender.console2.layout.ConversionPattern= %p %c{1}
    (%F:%M(%L)) - %m%n 

    Note: the only difference between the two appenders are the appenders' name and ConversionPattern property.

  3. a more detailed discussion of log4j can be found Short introduction to log4j