Enhancing Java Console Logs: A Practical Guide to Log4j2 Pattern Layout
:: published on
At development time, I always watch the application logs. Spring Boot demonstrates that having nicely formatted and styled logs helps make them more readable.
Since I started developing an application that does not use Spring Boot or Logback, I’ve needed something similar with Log4j2. Here is the pattern layout:
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue, TRACE=cyan} %style{%processId}{magenta} --- [%15.15t] %style{%-40.40c{1.}}{cyan} : %m %replace{%style{%X}{magenta}}{\{\}}{}%n" />
</Console>
%d{yyyy-MM-dd HH:mm:ss.SSS}
: Formats the logging date.%highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue, TRACE=cyan}
: Highlights the log level.%style{%processId}{magenta}
: Shows the processId, displayed in magenta.%style{%-40.40c{1.}}{cyan}
: Styles the logger name, formatted to a fixed width of 40 characters, left-justified, and displayed in cyan.: %m
: The actual log message.%replace{%style{%X}{bright_black}}{{}}{}
: For Mapped Diagnostic Context (MDC) data. %X prints MDC data, styled in bright_black, and the replace function removes curly braces {} from empty MDC data.%n
: A newline character, ensuring each log entry appears on a new line.
The Log4j2 documentation contains all the details about the pattern layout.