我需要以编程方式添加文件记录,并动态生成文件名。
我的代码是这样的:
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();
}
我看了一下食谱How to add Log4J2 appenders at runtime programmatically?和http://logging.apache.org/log4j/2.x/manual/customconfig.html#AddingToCurrent。
我的问题是:
有人可以提供一个带有最新API的下降示例到log4j2来动态添加文件记录吗?我使用org.apache.logging.log4j 2.8.1。
答案 0 :(得分:5)
根据评论中的其他信息,这是我的建议。我不认为您需要以编程方式执行此操作,原因是您在问题中提到的所有原因。
相反,您可以使用类似以下示例的内容配置log4j2系统。请注意,您不一定需要我只是用于测试的控制台appender。
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代码:
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!");
}
}
输出
我使用了“myFile”的程序参数,它生成了以下内容的文件:logs / myFile.txt:
[2017-05-03T11:20:37,653][INFO ][main] Here's some info!
您应该能够修改此示例以满足您的需求,您无需进行任何编程配置,从而避免了您提到的问题。