How to use the same logger to log different levels

2019-06-20 04:27发布

问题:

I have a log4j logger that currently writes the log both to console and to a file, which works fine.

Later I'd like to configure it to log INFO + ERROR to the logfile, but only show ERROR on console. What would I have to change to achieve this?

log4j.rootLogger=INFO, console, MyFileAppender

log4j.logger.org.apache.cxf=INFO, console
log4j.logger.org.apache.cxf.interceptor.LoggingInInterceptor=INFO, console
log4j.logger.org.apache.cxf.interceptor.LoggingOutInterceptor=INFO, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out

log4j.appender.MyFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.MyFileAppender.Append=true
log4j.appender.MyFileAppender.File=c:/logs.log

Further, I'd like to prevent the CXF XML requests to be logged in the file. But I want them still to be shown in the console. How?

回答1:

Appender based configuration

Configuring the log levels per each appender has to be done separately unless it is same as the root level configuration. Below sample log4.properties file is configured to log INFO and above into the console, but only ERROR and above into the file.

log4j.appender.[appender-name].Threshold=[Level]

Look at the last line of the below example (from "How to integrate log4j with your Java project").

# root level configurations 
log4j.rootLogger=INFO,console,file   

# configuration for console outputs  
log4j.appender.console=org.apache.log4j.ConsoleAppender  
log4j.appender.console.layout=org.apache.log4j.PatternLayout  

# configuration for file output (into a file named messages.log)  
log4j.appender.file=org.apache.log4j.RollingFileAppender  
log4j.appender.file.File=messages.log  
log4j.appender.file.layout=org.apache.log4j.PatternLayout 

# threshold for file output 
log4j.appender.file.Threshold=ERROR

Package based log levels

Any of the followings will help.

log4j.logger.[package]=[Level]
log4j.logger.[package]=[Level], [Appender]

As an example:

log4j.logger.org.apache.cxf=INFO, console


回答2:

As per this SO question (and its answer) you have to set a threshold on your appenders:

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=ERROR

log4j.appender.MyFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.MyFileAppender.Append=true
log4j.appender.MyFileAppender.File=c:/logs.log
log4j.appender.MyFileAppender.Threshold=INFO