动态创建Logback Logger和Appender

时间:2013-05-30 20:11:45

标签: java logging logback

我需要为动态加载和重新加载的类动态创建Logback记录器和各种位。我有一些可变数量的这些类,尽管它会少于150个。性能是一个很大的问题,这是一个高度线程和极其并发的环境,所以使用MDC的想法不会飞,因为当出现问题时可能会有数千次调用。我也不想直接将记录器传递给类,我希望他们只需使用getLogger将它们从空中拉出来。

每个类都必须将所有错误消息记录到它自己的错误文件中,并将所有错误消息记录到它自己的跟踪文件中。这两个文件都需要每晚滚动。此外,系统中记录的任何内容也必须最终出现在主系统日志中。

我已经创建了以下代码片段来尝试这个想法。它看起来像它可以工作,但结果不是我所期望的。这是可以直接运行的测试程序:

package logbacktesting;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.filter.LevelFilter;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;

public class Main {

    public static void main(String[] args) {

        Logger templateLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.myapp");
        LoggerContext loggerContext = templateLogger.getLoggerContext();

        String[] nameList = new String[] {"test1.class", "test2.class"};

        // Set up the pattern
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
        encoder.start();

        // Spin over the names to create all the needed objects
        for(int i = 0; i < nameList.length; i++) {

            String name = nameList[i];

            // Set up the roll over policies and the name when it rolls over
            TimeBasedRollingPolicy tracePolicy = new TimeBasedRollingPolicy();
            tracePolicy.setContext( loggerContext );
            tracePolicy.setFileNamePattern( name + "-Trace-%d{yyyy-MM-dd}.log" );
            tracePolicy.setMaxHistory( 30 );

            TimeBasedRollingPolicy errorPolicy = new TimeBasedRollingPolicy();
            errorPolicy.setContext( loggerContext );
            errorPolicy.setFileNamePattern( name + "-Error-logFile.%d{yyyy-MM-dd}.log" );
            errorPolicy.setMaxHistory( 30 );

            // Set up the filters to ensure things get split as expected
            LevelFilter traceFilter = new LevelFilter();
            traceFilter.setContext( loggerContext );
            traceFilter.setLevel( Level.TRACE );
            traceFilter.setOnMatch( FilterReply.ACCEPT );
            traceFilter.setOnMismatch( FilterReply.DENY );

            LevelFilter errorFilter = new LevelFilter();
            errorFilter.setContext( loggerContext );
            errorFilter.setLevel( Level.ERROR );
            errorFilter.setOnMatch( FilterReply.ACCEPT );
            errorFilter.setOnMismatch( FilterReply.DENY );

            // Set up the trace and error appenders
            RollingFileAppender rollingFileAppenderTrace = new RollingFileAppender();
            rollingFileAppenderTrace.setContext(loggerContext);
            rollingFileAppenderTrace.setName(name + "-Trace");
            rollingFileAppenderTrace.setFile(name + "-Trace.log");
            rollingFileAppenderTrace.setEncoder(encoder);
            rollingFileAppenderTrace.setRollingPolicy( tracePolicy );
            rollingFileAppenderTrace.addFilter( traceFilter );
            tracePolicy.setParent( rollingFileAppenderTrace );

            RollingFileAppender rollingFileAppenderError = new RollingFileAppender();
            rollingFileAppenderError.setContext(loggerContext);
            rollingFileAppenderError.setName(name + "-Error");
            rollingFileAppenderError.setFile(name + "-Error.log");
            rollingFileAppenderError.setEncoder(encoder);
            rollingFileAppenderError.setRollingPolicy( errorPolicy );
            rollingFileAppenderError.addFilter( errorFilter );
            errorPolicy.setParent( rollingFileAppenderError );

            // Start everything
            tracePolicy.start();
            errorPolicy.start();
            traceFilter.start();
            errorFilter.start();
            rollingFileAppenderTrace.start();
            rollingFileAppenderError.start();

            // attach the rolling file appenders to the logger
            Logger logger = (ch.qos.logback.classic.Logger) loggerContext.getLogger(name);
            logger.addAppender(rollingFileAppenderTrace);
            logger.addAppender(rollingFileAppenderError);

        }

        StatusPrinter.print(loggerContext);

        // Test it to see what happens
        for(int i = 0; i < nameList.length; i++) {

            String name = nameList[i];

            Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(name);
            logger.error("error message" );
            logger.warn("warn message" );
            logger.info("info message" );
            logger.debug("debug message" );
            logger.trace("trace message" );
        }

        Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.myapp");
        logger.error( "generic error message ");


    }

}

这是logback.xml文件:     

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logFile.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

如果您运行此代码,它将正确地将所有内容记录到主日志文件中。它将按预期创建2个跟踪和2个错误日志。但是跟踪消息都不会在跟踪日志文件中结束,并且两个错误消息都将在class2错误文件中结束。它的作用就像所有4个appender被添加到同一个记录器中,只有最后添加的appender实际上有效。我很想知道我在这里做什么。谢谢!

2 个答案:

答案 0 :(得分:5)

  

一切都进入主日志文件

这是因为所有记录器都将从ROOT记录器“继承”appender,您可以使用logger.setAdditive(false)来禁用此行为。

但我不知道为什么你没有任何跟踪日志......

也许这两个链接会给你一些灵感

Logback - set log file name programmatically

how-to-create-logback-loggers-dynamically-pragmatically

答案 1 :(得分:2)

上面的代码有几个问题。首先是Ceki所说的:你不能共享编码器。在循环中创建两个编码器改变了正确方向的行为。第二个问题是在XML文件中,根级别应该是跟踪,而不是调试。编码器改变后很明显。