Reputation: 6650
According to the Log4j 2 manual:
A LoggerConfig (including the root LoggerConfig) can be configured with properties that will be added to the properties copied from the ThreadContextMap. These properties can be referenced from Appenders, Filters, Layouts, etc just as if they were part of the ThreadContext Map.
However, I can't find how to do it. I have tried the following:
<Configuration>
<Appenders>
<Console name="stdout">
<PatternLayout charset="UTF-8">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{concern}] [%-5p] %c: %m%n</Pattern>
</PatternLayout>
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="stdout"/>
</Root>
<Logger name="com.example.log4j2.Foo">
<Properties>
<Property name="concern">foo</Property>
</Properties>
</Logger>
<Logger name="com.example.log4j2.Bar">
<Properties>
<Property name="concern">bar</Property>
</Properties>
</Logger>
</Loggers>
</Configuration>
With this configuration, the ThreadContextMap won't have any "concern" key and the StatusLogger will output:
ERROR Attempted to assign attribute Properties to list of type class org.apache.logging.log4j.core.lookup.Interpolator which is incompatible with class org.apache.logging.log4j.core.config.Property.
ERROR logger Logger has no parameter that matches element Properties
How can I have attributes attached to log events that depend on the logger?
Upvotes: 1
Views: 1704
Reputation: 6650
I found the solution by searching the log4j git repo: the <Property/>
elements must be direct childs of the <Logger/>
elements.
See the log4j-loggerprops.xml file from the test resources:
<Configuration status="OFF" strict="false" name="DSI">
<Properties>
<Property name="test2">test2default</Property>
<Property name="attribKey" value="attribValue" />
<Property name="duplicateKey" value="attribValue">nodeValue</Property>
<Property name="test5">${sys:test:-${sys:test2}}</Property>
</Properties>
<Appenders>
<List name="List">
<PatternLayout pattern="[%-5level] %c{1.} user=%X{user} phrasex=%X{phrasex} test=%X{test} test2=$${sys:test2} test3=$${sys:test3:-Unknown} test4=$${sys:test3:-${sys:test}} test5=${test5} attribKey=$${attribKey} duplicateKey=$${duplicateKey}%msg%n" />
</List>
</Appenders>
<Loggers>
<Logger name="org.apache.logging.log4j.core" level="debug" additivity="false">
<Property name="user">$${sys:user.name}</Property>
<Property name="phrasex">${sys:user.phrasex:-****}</Property>
<Property name="test">${sys:test}</Property>
<AppenderRef ref="List"/>
</Logger>
<Root level="debug">
<Property name="user">${sys:user.name}</Property>
<Property name="phrasex">${sys:user.phrasex:-****}</Property>
<Property name="test">${sys:test}</Property>
<AppenderRef ref="List" />
</Root>
</Loggers>
</Configuration>
Upvotes: 1