In my spring boot application, we need to add an extra tag( key/value pair) only for some specific log messages to highlight that these are some special purpose logs and not for others.
Project log4j2.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<JsonTemplateLayout eventTemplateUri="classpath:LogstashLayout.json">
</JsonTemplateLayout>
</Console>
</Appenders>
<Loggers>
<AsyncRoot level="info" additivity="false">
<AppenderRef ref="console" />
</AsyncRoot>
</Loggers>
</Configuration>
What is the standard recommended approach to do this? is this need to be done some sort of filter configurations?
Think that marker would be helpful to you although it can just tag a log message but cannot add a key/value to it. After you use it to tag the log messages , you can configure a filter in the configuration to determine whether a message with certain tag should be displayed or not.
For example, you can tag the log messages something like:
public class Foo {
private static final Marker TAG1 = MarkerManager.getMarker("TAG1");
private static final Marker TAG2 = MarkerManager.getMarker("TAG2");
private static final Marker TAG3 = MarkerManager.getMarker("TAG3");
void test(){
log.info(TAG1, "message with tag1");
log.info(TAG1, "message with tag1");
log.info(TAG2, "message with tag2");
log.info(TAG2, "message with tag2");
log.info(TAG3, "message with tag3");
log.info(TAG3, "message with tag3");
}
}
Then with this filter configuration :
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{ISO8601} |%t| %5p | %c{1} | %L | %m%n" />
<Filters>
<MarkerFilter marker="TAG1" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<MarkerFilter marker="TAG2" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<MarkerFilter marker="TAG3" onMatch="DENY" onMismatch="NEUTRAL"/>
</Filters>>
</Console>
</Appenders>
Only messages with TAG1 , TAG2 and no tags will be displayed to console. Messages with TAG3 will not.
And if the filter configuration is :
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{ISO8601} |%t| %5p | %c{1} | %L | %m%n" />
<Filters>
<MarkerFilter marker="TAG1" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<MarkerFilter marker="TAG2" onMatch="ACCEPT" onMismatch="NEUTRAL"/>
<MarkerFilter marker="TAG3" onMatch="DENY" onMismatch="DENY"/>
</Filters>>
</Console>
</Appenders>
Then only messages with TAG1 , TAG2 will be displayed. Messages with TAG3 or no tags will not.
The filter can be configured at the logger level or appender level. And I found this answer is helpful to understand the basic idea of how does the filter works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With