简体   繁体   English

使用Log4j2 2.8.1在运行时动态添加文件日志记录

[英]Add file logging dynamically at runtime with Log4j2 2.8.1

I am in need of adding programmatically a file logging, with file name generated dynamically. 我需要以编程方式添加文件日志记录,并动态生成文件名。

My code is like this: 我的代码是这样的:

private static final Logger LOGGER = LogManager.getLogger(Archiver.class);

public static void openLogfile(String folder) {
    String dateTime = "TODO";
    String fileName = folder + "upload" + dateTime + ".log";
    LOGGER.info("Opening " + fileName + " for logging.");
    // setting up a FileAppender dynamically...
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, config, null,
            null, true, true, null, null);
    Appender appender = FileAppender.createAppender(fileName, "false", "false", "File", "true",
            "false", "false", "4000", layout, null, "false", null, config);
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};

    LoggerConfig loggerConfig = LoggerConfig.createLogger(true, Level.DEBUG, "org.apache.logging.log4j", "", refs,
            null, config, null);

    loggerConfig.addAppender(appender, null, null);
    config.addLogger("org.apache.logging.log4j", loggerConfig);
    ctx.updateLoggers();

}

I took a look at the recipe How to add Log4J2 appenders at runtime programmatically? 我看了一下如何在运行时以编程方式添加Log4J2追加器的配方 and to http://logging.apache.org/log4j/2.x/manual/customconfig.html#AddingToCurrent . 并访问http://logging.apache.org/log4j/2.x/manual/customconfig.html#AddingToCurrent

My problems are: 我的问题是:

  • The example on the log4j2 doc stated above would not compile, it is outdated, had to add few parameters without much idea what they are, usually I added nulls. 上面提到的log4j2 doc上的示例无法编译,这已经过时了,不得不添加一些参数而又不知道它们是什么,通常我会添加null。
  • The very methods used in the documentation are now deprecated; 现在不推荐使用本文档中使用的方法。
  • The file is being created but no logs appear there albeit having output on the console, and after program is quit, nothing is flushed in the file either. 正在创建文件,但是没有日志显示,尽管控制台上有输出,并且退出程序后,文件中也没有刷新。

Could somebody please provide a descent example with a most recent API to log4j2 to dynamically add file logging? 有人可以提供一个带有最新API的后代示例到log4j2来动态添加文件日志记录吗? I use org.apache.logging.log4j 2.8.1. 我使用org.apache.logging.log4j 2.8.1。

Based on additional information in the comments, here is my suggestion. 根据评论中的其他信息,这是我的建议。 I don't think you need to do this programmatically for all the reasons you mentioned in your question. 我不认为您出于问题中提到的所有原因都需要以编程方式进行此操作。

Instead you can configure the log4j2 system using something like the following example. 相反,您可以使用以下示例来配置log4j2系统。 Note that you do not necessarily need the console appender I simply used that for testing. 请注意,您不一定需要控制台附加程序,我只是将其用于测试。

log4j2.xml content: log4j2.xml内容:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="[%date{ISO8601}][%-5level][%t] %m%n" />
        </Console>
        <File
            fileName="logs/${ctx:fileName}.txt"
            name="logFile">
            <PatternLayout>
                <Pattern>[%date{ISO8601}][%-5level][%t] %m%n</Pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Logger name="example" level="TRACE" additivity="false">
            <AppenderRef ref="STDOUT" />
            <AppenderRef ref="logFile" />
        </Logger>
        <Root level="WARN">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>

Java code: Java代码:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;

public class LogFileNameBasedOnArg0Main {

    public static void main(String[] args) {
        ThreadContext.put("fileName", args[0]);
        Logger log = LogManager.getLogger();
        log.info("Here's some info!");
    }

}

Output: 输出:

I used a program argument of "myFile" which generated the file: logs/myFile.txt with the following content: 我使用了一个程序参数“ myFile”来生成文件:logs / myFile.txt,内容如下:

[2017-05-03T11:20:37,653][INFO ][main] Here's some info!

You should be able to modify this example to meet your needs and you won't have to do any programmatic configuration thus avoiding the issues you mentioned. 您应该能够修改此示例以满足您的需求,并且无需进行任何程序配置,从而避免了您提到的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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