简体   繁体   中英

Is it possible to log only one level messages with Log4J

If I set the log level to DEBUG, All messages with log level >= DEBUG will be logged/printed. But can I set log level to only DEBUG, such that messages with log level only with DEBUG will be printed. Or can give a range like print all messages whose log level is >=DEBUG but < ERROR?

Maybe you can use a LevelMatchFilter?

At some situation, You have to write logs to different outputs according to the level. how can it be done by simply configuration of Log4j? There are some methods below.

http://wiki.apache.org/logging-log4j/LogToAppenderByLevel

As said Jarle you have to use LevelMatchFilter . I will demonstrate it with one simple exam:

log4j.rootLogger = WARN, admin 
log4j.appender.admin=org.apache.log4j.rolling.RollingFileAppender
        log4j.appender.admin.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
        log4j.appender.admin.rollingPolicy.FileNamePattern = Files\\TestLevels-%d{dd-MM-yyy}.txt
        log4j.appender.admin.layout = org.apache.log4j.PatternLayout
        log4j.appender.admin.layout.ConversionPattern = Date: %d{dd-MM-yyyy} Time: %d{HH:mm:ss} Message [%m]%n
        log4j.appender.admin.filter.01=org.apache.log4j.varia.LevelMatchFilter
        log4j.appender.admin.filter.01.LevelToMatch=FATAL
        log4j.appender.admin.filter.01.AcceptOnMatch=false
        log4j.appender.admin.filter.02=org.apache.log4j.varia.LevelMatchFilter
        log4j.appender.admin.filter.02.LevelToMatch=ERROR
        log4j.appender.admin.filter.02.AcceptOnMatch=true
        log4j.appender.admin.filter.03=org.apache.log4j.varia.LevelMatchFilter
        log4j.appender.admin.filter.03.LevelToMatch=WARN
        log4j.appender.admin.filter.03.AcceptOnMatch=false

In my source I append only ERROR messages to file with name TestLevels.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM