Reputation: 75
I am developing a project with lots of external libraries that most are using Log4J. Currently, we are identifying them and turning their log level to OFF one by one in log4j.properties
. I was wondering if there is a more efficient solution that one can turn off logger on all packages except one?
I researched a lot on StackOverflow, but almost all answers are revolving around explicitly turning off the loggers for external libraries individually, which is not an efficient solution in our case.
For reference, our log4j.properties
looks like this:
# Define the root logger with appender file
log4j.rootLogger = DEBUG, stdout
# here we exclude loggers for external packages one by one
log4j.logger.com.github.external1 = OFF
log4j.logger.com.github.external2 = OFF
log4j.logger.org.external3 = OFF
....
log4j.logger.com.example.external100 = OFF
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=./log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
Upvotes: 2
Views: 883
Reputation: 9463
Log4j organizes it's loggers in a hierarchy. If you turn off the root logging you deactivate all but can still turn on your well known packages, which are a lot less than all the others. Here is an example based on yours:
# Define the root logger with appender file and turn all the categories off
log4j.rootLogger = OFF, stdout
# Now turn on only my packages
log4j.logger.com.mycompany = DEBUG
# here we exclude loggers for external packages one by one
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=./log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
However be aware this configuration file works on Log4j 1. You want to migrate to Log4j 2.17.x to mitigate that famous vulnerability.
Upvotes: 1