在飞行中创建新的滚动文件LOG4j2 2.6

时间:2017-02-03 11:12:12

标签: java logging log4j2

我正在尝试基于log4j2.xml主要文件在我的应用程序中快速创建一个新的记录器配置。代码将自我解释:

XML文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="5">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%-d{yyyy MMM dd HH:mm:ss,SSS} %5p %c{1} - %m%n" />
        </Console>

        <RollingFile name="file" fileName="./log/application.log"
            filePattern="./log/devfix-%-d{yyyy-MM-dd}.log">
            <PatternLayout pattern="%-d{yyyy-MM-dd HH:mm:ss.SSS} %5p %c{1} - %m%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100MB" />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>


        <Async name="ASYNC" bufferSize="2048">
            <AppenderRef ref="file" />
            <AppenderRef ref="STDOUT" />
        </Async>

        <JMS name="jmsQueue" destinationBindingName="logQueue"
            factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory"
            factoryBindingName="ConnectionFactory" providerURL="tcp://xxxx:xxxxx?jms.useAsyncSend=true">
            <PatternLayout pattern="%-d{yyyy-MM-dd HH:mm:ss.SSS} %5p %c{1} - %m%n" />
        </JMS>

        <RollingFile name="fixfile" fileName="./log/fix.log"
            filePattern="./log/fix-%-d{yyyy-MM-dd-HH}.log">
            <PatternLayout pattern="%-d{yyyy MMM dd HH:mm:ss,SSS} %c{1} - %m%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="50MB" />
            </Policies>
            <DefaultRolloverStrategy max="10" />
        </RollingFile>

    </Appenders>

    <Loggers>
        <Logger name="jmsLogger" additivity="false" level="OFF">
            <AppenderRef ref="jmsQueue" />
        </Logger>

        <Logger name="org.hibernate" level="WARN">
        </Logger>
        <Logger name="FIX_CONFIG" level="INFO" additivity="false">
            <AppenderRef ref="fixfile" />
        </Logger>
        <Root level="info">
            <AppenderRef ref="ASYNC" />
        </Root>

    </Loggers>
</Configuration>

所以在那之后,在代码中,我使用一种方法来创建一个新的rolligFileAppender。

private static Logger getLogger(String platformName) throws IOException {

    /*Using a commun configuration to find the new Path for the plaform log file*/
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    RollingFileAppender fixAppender = (RollingFileAppender) config.getAppender("fixfile");
    if(null == fixAppender) {
        Logger logger = LogManager.getLogger(platformName);
        logger.error("Missing fixfile log4j appender in configuration");
        return logger;
    }
    String fileName = fixAppender.getFileName();
    if (null != fileName && fileName.toLowerCase().endsWith(".log"))
        try { // remove empty fix.log file created by defaults
            new File(fileName).delete();
        } catch (Exception e) {
        }

    /*construction of the new file name depending on the platform*/
    int slashIndex = null != fileName ? fileName.lastIndexOf("/") : -1;
    fileName = slashIndex >= 0 ? fileName.substring(0, slashIndex + 1) + platformName.toLowerCase() + ".log" : platformName.toLowerCase() + ".log";

    /*construction of the new file Pattern  depending on the platform*/
    String fileNamePattern = fixAppender.getFileName();
    int slashIndexPattern = null != fileNamePattern ? fileNamePattern.lastIndexOf("/") : -1;
     fileNamePattern = slashIndex >= 0 ? fileNamePattern.substring(0, slashIndexPattern + 1) + platformName.toLowerCase()+"-%-d{yyyy-MM-dd-HH}.log" : platformName.toLowerCase() + "-%-d{yyyy-MM-dd-HH}.log";

    ConfigurationBuilder< BuiltConfiguration > builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel( Level.INFO);
    builder.setConfigurationName("RollingBuilder");


    // create a console appender
    AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
        ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout")
        .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
    builder.add( appenderBuilder );



    // create a rolling file appender
    LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
        .addAttribute("pattern", " %-d{yyyy-MM-dd HH:mm:ss.SSS} %5p %c{1} - %m%n");
    ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
        .addComponent(builder.newComponent("TimeBasedTriggeringPolicy"));

      appenderBuilder = builder.newAppender("file2", "RollingFile")
        .addAttribute("fileName", fileName)
        .addAttribute("filePattern", fileNamePattern)
        .add(layoutBuilder)
        .addComponent(triggeringPolicy);
    builder.add(appenderBuilder);

    // create the new logger
    builder.add( builder.newLogger( platformName.toLowerCase(), Level.INFO )
        .add( builder.newAppenderRef( "file2" ) )
        .addAttribute( "additivity", false ) );

    builder.add( builder.newRootLogger( Level.INFO )
        .add( builder.newAppenderRef( "file2" ) ) );


    LoggerContext newctx = Configurator.initialize(builder.build());
    return newctx.getLogger(platformName.toLowerCase());

}

问题是我无法创建这个新的记录器。例如,我用平台名称参数=“test”调用此函数。 ./log/test.log文件已正确创建,但我无法记录任何内容。

当我尝试进入调试时,最后一个语句LoggerContext newctx = Configurator.initialize(builder.build()),我注意到newctx指向我的log4j2.xml文件,因此用他的所有参数初始化,并且忽略我的指令builer.Build()。

你知道为什么会这样吗?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

解决了,

我没有使用正确的选项,我按照https://logging.apache.org/log4j/log4j-2.4/manual/customconfig.html

中的描述

以编程方式添加到当前配置