Conversion pattern examples

Simple (date, level, logger, message):

%d [%p] %c{1} - %m%n

2015-07-26 15:01:33,665 [DEBUG] MyClass - This is a debug message.
2015-07-26 15:01:33,665 [INFO] MyClass - This is an info message.

Fix the length of level to make it pretty:

%d [%-6p] %c{1} - %m%n

2015-07-26 15:01:09,341 [DEBUG ] MyClass - This is a debug message.
2015-07-26 15:01:09,342 [INFO  ] MyClass - This is an info message.

Print full package names of logger:

%d [%-6p] %c - %m%n

2015-07-26 15:02:05,189 [DEBUG ] hu.daniel.hari.log4jtester.log4j.renderer.scenario.worker.foo.MyClass - This is a debug message.

Or print only last two package name:

%d [%-6p] %c{3} - %m%n

2015-07-26 15:02:57,468 [DEBUG ] worker.foo.MyClass - This is a debug message.

Custom format the date:

%d{yyyy/MM/dd HH:mm:ss,SSS} [%-6p] %c{1} - %m%n

2015/07/26 15:03:30,231 [DEBUG ] MyClass - This is a debug message.

Print the caller class, method, source file and line number:

%d [%-6p] %C{1}.%M(%F:%L) - %m%n

2015-07-26 15:07:10,332 [DEBUG ] MyClass.logDebug(MyClass.java:27) - This is a debug message.

Print the thread name:

%d [%-6p] [%t] %c{1} - %m%n

2015-07-26 15:37:24,444 [DEBUG ] [main] MyClass - This is a debug message.

Full pattern:

%sn %d{yyyy/MM/dd HH:mm:ss,SSS} %r [%-6p] [%t] %c{3} %C{3}.%M(%F:%L) - %m%n

163 2015/07/26 15:46:12,072 679487 [DEBUG ] [main] worker.foo.MyClass worker.foo.MyClass.logDebug(MyClass.java:27) - This is a debug message.


Log4j configuration example

logj4.properties:

log4j.rootLogger=INFO, STDOUT

#appenders
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.Target=System.out
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=[%d{dd/MM/yyyy HH:mm:ss,SSS}] [%-7p] %c{1}:%L (%t) - %m%n

References

Log4j 2.x pattern reference: http://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout

Log4j 1.x PatternLayout API docs: https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html


About

This java web-app has implemented in GWT, uses log4j2 2.6.2 and log4j 1.2.17 library both (To detect the pattern is version 1 or 2). Before log4j 1.2.16 only the old school PatternLayout was existed, but log4j 1.2.16 introduced EnhancedPatternLayout with some new conversion specifiers. Log4j2's PatternLayout compliant with previous versions but has much more features, e.g. colors.

About Dániel Hári

Dániel Hári is the founder of log4jtester.com, cleancodejava.com. Who is an enthusiastic Java developer who enhances his knowledge by continously searching for best practices and modern technologies. Engaged to clean coding, and honors the engineering profession as releasing quality work.