问题
I have the log4j2.xml which is partially configured as:
<Loggers>
<Root level="debug" includeLocation="true">
<AppenderRef ref="FileInfo" level="info" />
<AppenderRef ref="FileDebug" level="debug" />
</Root>
<Logger name="com.mycompany.domain.XYZ" level="TRACE" />
<Logger name="com.mycompany.domain.ABC" level="TRACE" />
</Loggers>
However, the TRACE messages doesn't come in either of the File appenders (FileInfo/FileDebug). When I change the FileDebug log level = "TRACE", then TRACE messages come.
Question: There are multiple places to specify log 'level'. Whats the precedence order for these levels. I thought level defined at Logger tag should be highest.
回答1:
You should take the time to read the log4j2 manual regarding the architecture of log4j2. In particular the sections on "LoggerConfig" and "Appender".
The behavior you describe is due to the fact that you don't have any appenders associated with your com.mycompany.domain.XYZ
and com.mycompany.domain.ABC
loggers, and the default value of additivity is true
.
When a message reaches one of the com.mycompany...
loggers and is TRACE
level it will be accepted by the logger and sent to all appenders of that logger - which is NONE since there are no appenders for these loggers.
Next, since additivity is true
by default the message goes to the appenders of the next ancestor in the logger hierarchy, which is root in your case. The level of the root logger does not affect whether the message is accepted since it was already accepted by the child logger. However, the message still would not appear in the output since you have the appenders' levels set more specific than TRACE
, so the appenders both reject the message.
This brings me to your question about precedence. The answer to which is that the logger's level takes precedence over the appender's level. If the message is rejected by the logger it will never reach the appenders of that logger. If the message is accepted by the logger it can still be rejected by the appender if the appender's level is more specific than the message level. The tricky part is that when additivity is true
(which it is by default) the appenders of ancestor loggers are treated as appenders of the child logger as I explained above.
In other words - since TRACE
is the second least specific level you would need to set both your logger and your appender to a level that is TRACE
or lower (e.g. ALL
) in order to see those messages appear in the output. Alternatively you can simply set your logger to a level of TRACE
or lower and do not set the level on the appender.
来源:https://stackoverflow.com/questions/51429472/log4j2-log-level-precedence