[英]Log4j2: Programmatically create file appender with timestamp in the filename
可以使用[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
這將在file-with-date-2017-11-30.log
生成日志文件。 如何使用程序化配置實現相同的行為? 到目前為止,這是我嘗試過的:
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();
但這會產生以下文件: file-with-date-${date:yyyy-MM-dd}.log
。 因此,使用屬性配置:使用程序創建的附加程序${date:yyyy-MM-dd}.log
創建具有當前日期的日志文件。 ${date:yyyy-MM-dd}.log
將被忽略。
顯然, 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.