Java 当我们在 log4j 中使用基于大小的日志文件时,如何在日志文件名中添加时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18081172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:16:13  来源:igfitidea点击:

How to add timestamp to the log file name when we are using size based log files in log4j?

javalog4j

提问by rana

I want to create size based log files. I am setting the following entry in the log4j.properties file:

我想创建基于大小的日志文件。我在 log4j.properties 文件中设置以下条目:

log4j.appender.UserFileAppenderDebug=org.apache.log4j.RollingFileAppender

log4j.appender.UserFileAppenderDebug.Threshold=TRACE

log4j.appender.UserFileAppenderDebug.File=../log/coordinator-debug.log

log4j.appender.UserFileAppenderDebug.MaxFileSize=1KB

log4j.appender.UserFileAppenderDebug.MaxBackupIndex=7

log4j.appender.UserFileAppenderDebug.layout=org.apache.log4j.PatternLayout

log4j.appender.UserFileAppenderDebug.layout.ConversionPattern=%m%n

multiple log files are created based on size but with following names:

根据大小创建多个日志文件,但名称如下:

-rw-r--r-- 1 root root   32 Aug  6 11:28 coordinator-debug.log

-rw-r--r-- 1 root root 1.1K Aug  6 11:28 coordinator-debug.log.1

-rw-r--r-- 1 root root 1.1K Aug  6 11:28 coordinator-debug.log.2

-rw-r--r-- 1 root root 1.2K Aug  6 11:28 coordinator-debug.log.3

-rw-r--r-- 1 root root 1.1K Aug  6 11:28 coordinator-debug.log.4

-rw-r--r-- 1 root root 1.1K Aug  6 11:28 coordinator-debug.log.5

-rw-r--r-- 1 root root 1.1K Aug  6 11:28 coordinator-debug.log.6

-rw-r--r-- 1 root root 1.1K Aug  6 11:28 coordinator-debug.log.7

I would like to have the file name as follows

我想要文件名如下

coordinator-debug.log.2013-08-01 11:28:39, 232

I would appreciate if you please share your comments/suggestions.

如果您能分享您的意见/建议,我将不胜感激。

Thanks.

谢谢。

回答by MrSimpleMind

Have you tried:

你有没有尝试过:

log4j.appender.UserFileAppenderDebug.DatePattern='.'yyyy-MM-dd_HH-mm-ss

log4j.appender.UserFileAppenderDebug.DatePattern='.'yyyy-MM-dd_HH-mm-ss

(remember that your filename will not allow : e.g 11:28:39, you will need to replace them to e.g. 11-28-39 )

(请记住,您的文件名不允许:例如 11:28:39,您需要将它们替换为例如 11-28-39 )

(edited)

(已编辑

Sorry, I thought you used the *Daily*RollingFileAppender...

抱歉,我以为你使用了 * Daily*RollingFileAppender ...

There are RollingPolicys that you might use to get filename pattern for the RollingFileAppender.

您可以使用 RollingPolicys 来获取 RollingFileAppender 的文件名模式。

E.g.

例如

log4j.appender.UserFileAppenderDebug.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy

log4j.appender.UserFileAppenderDebug.RollingPolicy.FileNamePattern=../log/coordinator-debug.log.%d{yyyy-MM-dd-HH-mm-ss}