Is it possible to change the log level of a package in log4j?
Currently I have a library that is logging certain information as ERROR. If I change my log4j settings like this:
log4j.logger.com.company.theirpackage.foo=OFF
that will completely disable the library's logging altogether. However, what I'd really like is to still see the information, but have it logged at a WARN or INFO level. In other words, when that particular code calls log.error(开发者_运维知识库)
, I want it to be as if they had called log.warn()
or log.info()
instead.
Is there a way to do this with log4j?
Not directly, but you could write a custom appender that intercepts the calls, checks the levels, and then prints them at whatever level you want. Or, you could do some aspect oriented programming and intercept/change their calls.
But why would you want to change the level they log it at?
I think this is possible, by implementing a Filter, in which the level inside a LoggingEvent is changed when it matches certain conditions.
There are multiple ways to do that. I think the easiest way to do that is to use custom Appender.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="console-> %-5p %c{1}:%L - %m%n" />
</Console>
<Console name="CUSTOM_ERROR_STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="dependent-> %-5p{ERROR=WARN} %c{1}:%L - %m%n" />
</Console>
</Appenders>
<Loggers>
<!-- Root logger referring to console appender -->
<Root level="INFO">
<AppenderRef ref="STDOUT"/>
</Root>
<Logger name="com.my.LogTest" level="INFO" additivity="false">
<AppenderRef ref="CUSTOM_ERROR_STDOUT" />
</Logger>
</Loggers>
</Configuration>
Here I convert all the error logs into warning for that specific class com.my.LogTest. You can find more info about Appender Layouts here. It has pattern selector option which allows you to choose different pattern based on your condition.
精彩评论