按级别单独的日志记录日志

时间:2013-01-30 10:10:16

标签: java slf4j logback

是否可以单独记录每个级别,以便使用Logback获得DEBUG.log,WARN.log,INFO.log ...

3 个答案:

答案 0 :(得分:2)

您可以写一个filter之类的

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

public class WarnFilter extends Filter<ILoggingEvent> {

    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (Level.DEBUG.equals(event.getLevel())) {
            return FilterReply.ACCEPT;
        } else {
            return FilterReply.DENY;
        }
    }

}

然后使用过滤器为

配置一个appender
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <filter class="logback.WarnFilter" />
    <encoder>
        <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c - %m [%class %M %L] %ex{full} %n</pattern>
    </encoder>
</appender>

答案 1 :(得分:2)

没有必要编写新的过滤器,LevelFilter将很快适合您的情况:

        <configuration>
          <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
              <level>INFO</level>
              <onMatch>ACCEPT</onMatch>
              <onMismatch>DENY</onMismatch>
            </filter>
            <encoder>
              <pattern>
                %-4relative [%thread] %-5level %logger{30} - %msg%n
              </pattern>
            </encoder>
          </appender>
          <root level="DEBUG">
            <appender-ref ref="CONSOLE" />
          </root>
        </configuration>

答案 2 :(得分:0)

像这样配置log4j.properties

log4j.rootLogger=InfoAppender, DebugAppender
# setup Info
log4j.appender.InfoAppender=org.apache.log4j.RollingFileAppender
log4j.appender.InfoAppender.Threshold=INFO
log4j.appender.InfoAppender.File=quiet.log
...


# setup debug
log4j.appender.DebugAppender=org.apache.log4j.RollingFileAppender
log4j.appender.DebugAppender.Threshold=DEBUG
log4j.appender.DebugAppender.File=loud.log