如何使用logback.xml为stdout和文件创建2个不同的日志级别?

时间:2016-06-13 10:44:38

标签: exception-handling logback

下面是我的logback.xml 我添加了过滤器类来设置不同的日志级别,但它似乎不起作用。

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
    **<filter class ="ch.qos.logback.classic.filter.ThresholdFilter"><level>WARN</level></filter>**
        <encoder>
            <charset>UTF-8</charset>
            <Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    **<filter class ="ch.qos.logback.classic.filter.ThresholdFilter"><level>INFO</level></filter>**

        <file>application.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover. Make sure the path matches the one in the file element or else
             the rollover logs are placed in the working directory. -->
            <fileNamePattern>/srv/logs/application_%d{yyyy-MM-dd}.%i.log</fileNamePattern>

            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>5MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- keep 30 days' worth of history -->
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>


</configuration>

这是我使用logback配置的java代码。

public class APIController {

    private static final Logger logger = LoggerFactory.getLogger(APIController.class);

    ...
    private void handleException(Exception ex, String message) {
        logger.warn(message);

        if(logger.isInfoEnabled()){
        ex.printstacktrace();
        }
    }

}

但我仍然在控制台上看到堆栈跟踪。我应该如何保留2个不同的日志级别

1 个答案:

答案 0 :(得分:0)

directly prints the trace to the standard error output例外的printstacktrace方法。如果要记录异常,则需要使用a logging command,例如

logger.info("An interesting exception happened", ex);