Log4j2 PatternLayout¶
Log4j2 PatternLayout is a flexible configuration component that allows developers to customize the format of log output.^[600-developer__java__3-party__java-log4j2.md]
Syntax and Usage¶
In XML configurations, the PatternLayout is implemented using the <PatternLayout> element.^[600-developer__java__3-party__java-log4j2.md] The specific format of the log line is defined by the pattern attribute within this element.^[600-developer__java__3-party__java-log4j2.md]
Configuration Strategies¶
To promote consistency and maintainability across different appenders, it is a common practice to define the pattern string as a global property and then reference it.^[600-developer__java__3-party__java-log4j2.md]
For example, a property named LOG_PATTERN can be defined in the <Properties> section:^[600-developer__java__3-party__java-log4j2.md]
<Properties>
<Property name="LOG_PATTERN">[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</Property>
</Properties>
This property can then be reused by multiple PatternLayout instances via the ${LOG_PATTERN} syntax, ensuring that the [[Logging]] output format remains uniform whether writing to a file or the console.^[600-developer__java__3-party__java-log4j2.md]
Example¶
The following XML demonstrates a PatternLayout applied to a Console appender using the referenced property:^[600-developer__java__3-party__java-log4j2.md]
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
</Appenders>
Sources¶
^[600-developer__java__3-party__java-log4j2.md]