log4j: logging a package, but excluding its sub-pa

2019-05-11 10:35发布

问题:

Hi I'd like to exclude certain subpackages from being logged by one of my loggers, as they are being logged by another logger. Eg.

com.mysite.app = logger1
com.mysite.app.news = logger2
com.mysite.app.events = logger3

I'd like logger1 to only log anything with com.mysite.app (including com.mysite.app.utilities) not logged by logger2 and logger3. How could I do that?

(help in properties format please, XML format for other's reference for bonus points)

回答1:

I always used to think that log4j.logger.com.mysite.app = logger1 takes care of logging messages from subpackages too into logger1.

If you really don't want logger2 and logger3's messages from interfering with those of logger1, you need to set their additivity to false.

log4j.additivity.com.mysite.app.news=false
log4j.additivity.com.mysite.app.events=false


回答2:

Have a try:

log4j.logger.com.mysite.app=info, stdout
log4j.additivity.com.mysite.app=false

log4j.logger.com.mysite.app.news=off, stdout
log4j.additivity.com.mysite.app.news=false

log4j.logger.com.mysite.app.events=off, stdout
log4j.additivity.com.mysite.app.events=false


回答3:

For XML configuration:

<logger name="com.mysite.app.news" additivity="false">
    <appender-ref ref="logger2" />
</logger>    
<logger name="com.mysite.app.events" additivity="false">
    <appender-ref ref="logger3" />
</logger>