[英]Log4j2: Programmatically create file appender with timestamp in the filename
There is a possibility to create to add a timestamp to log4j2 logging files using [property] configuration: 可以使用[property]配置创建向log4j2日志文件添加时间戳的方法:
appender.FILE.type = FILE
appender.FILE.name = FILE
appender.FILE.fileName = file-with-date-${date:yyyy-MM-dd}.log
appender.FILE.layout.type = PatternLayout
appender.FILE.layout.pattern =[%p] %m%n
This will produce log files in the file-with-date-2017-11-30.log
. 这将在
file-with-date-2017-11-30.log
生成日志文件。 How can I achieve the same behavior using programmatic configuration? 如何使用程序化配置实现相同的行为? This is what I have tried so far:
到目前为止,这是我尝试过的:
PatternLayout layout = PatternLayout.newBuilder()
.withConfiguration(ctx.getConfiguration())
.withPattern("%m%n").build();
FileAppender fileAppender = FileAppender.newBuilder()
.withLayout(layout)
.withFileName( "file-with-date-${date:yyyy-MM-dd}.log")
.withName("pattern")
.build();
But this produces the following file: file-with-date-${date:yyyy-MM-dd}.log
. 但这会产生以下文件:
file-with-date-${date:yyyy-MM-dd}.log
。 So using properties configuration: a log file with current date is crated, using programmatically created appender ${date:yyyy-MM-dd}.log
gets ignored. 因此,使用属性配置:使用程序创建的附加程序
${date:yyyy-MM-dd}.log
创建具有当前日期的日志文件。 ${date:yyyy-MM-dd}.log
将被忽略。
Apparently StrSubstitutor can help in this situation. 显然, StrSubstitutor在这种情况下可以提供帮助。
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
String fileName = config.
getStrSubstitutor().replace("file-with-date-${date:yyyy-MM-dd}.log");
FileAppender fileAppender = FileAppender.newBuilder()
.withLayout(layout)
.withFileName(filename)
.withName("pattern")
.build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.