Java 如何将 log4j 配置为仅保留最近 7 天的日志文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3683364/
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
How to configure log4j to only keep log files for the last seven days?
提问by asmaier
I have the following logging problem with several Java applications using log4j
for logging:
我有几个log4j
用于日志记录的Java 应用程序的日志记录问题:
I want log files to be rotated daily, like
我希望每天轮换日志文件,例如
log.2010-09-10
log.2010-09-09
log.2010-09-08
log.2010-09-07
log.2010-09-06
log.2010-09-05
log.2010-09-04
But for data security reasons we are not allowed to keep log files for longer than seven days at my company. So the generation of the next next log file log.2010-09-11
should trigger the deletion of log.2010-09-04
. Is it possible to configure such a behaviour with log4j
? If not, do you know another elegant solution for this kind of logging problem?
但出于数据安全原因,我们不允许在我公司保留日志文件超过 7 天。所以下一个日志文件的生成log.2010-09-11
应该触发log.2010-09-04
. 是否可以配置这样的行为log4j
?如果没有,您是否知道此类日志记录问题的另一种优雅解决方案?
采纳答案by dogbane
You can perform your housekeeping in a separate script which can be cronned to run daily. Something like this:
您可以在单独的脚本中执行内务管理,该脚本可以每天运行。像这样的东西:
find /path/to/logs -type f -mtime +7 -exec rm -f {} \;
回答by dty
I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex
which you can set to limit the number of files. For example:
我假设您正在使用 RollingFileAppender?在这种情况下,它有一个名为的属性MaxBackupIndex
,您可以设置它来限制文件数量。例如:
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
回答by Qwerky
There's also a DailyRollingFileAppender; http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/DailyRollingFileAppender.html
还有一个 DailyRollingFileAppender; http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/DailyRollingFileAppender.html
Edit: After reading this worrying statement;
编辑:在阅读了这个令人担忧的声明之后;
DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender.
已观察到 DailyRollingFileAppender 出现同步问题和数据丢失。log4j extras 伴侣包括新部署应考虑的替代方案,并在 org.apache.log4j.rolling.RollingFileAppender 的文档中讨论。
from the above URL (which I never realised before), then this looks like a better bet; http://logging.apache.org/log4j/companions/extras/apidocs/index.html
从上面的 URL(我以前从未意识到过),那么这看起来是一个更好的选择;http://logging.apache.org/log4j/companions/extras/apidocs/index.html
回答by PhilDin
According to the following post, you can't do this with log4j: Use MaxBackupIndex in DailyRollingFileAppender -log4j
根据以下帖子,您不能使用 log4j 执行此操作:在 DailyRollingFileAppender -log4j 中使用 MaxBackupIndex
As far as I know, this functionality was supposed to make it into log4j 2.0 but that effort got sidetracked. According to the logback website, logback is the intended successor to log4j so you might consider using that.
据我所知,这个功能应该会加入到 log4j 2.0 中,但这项工作被搁置了。根据 logback 网站,logback 是 log4j 的预期继承者,因此您可以考虑使用它。
There's an API called SLF4J which provides a common API to logging. It will load up the actual logging implementation at runtime so depending on the configuration that you have provided, it might use java.util.log or log4j or logback or any other library capable of providing logging facilities. There'll be a bit of up-front work to go from using log4j directly to using SLF4J but they provide some tools to automate this process. Once you've converted your code to use SLF4J, switching logging backends should simply be a case of changing the config file.
有一个名为 SLF4J 的 API,它提供了一个通用的日志记录 API。它将在运行时加载实际的日志实现,因此根据您提供的配置,它可能使用 java.util.log 或 log4j 或 logback 或任何其他能够提供日志功能的库。从直接使用 log4j 到使用 SLF4J 需要一些前期工作,但它们提供了一些工具来自动化这个过程。将代码转换为使用 SLF4J 后,切换日志记录后端应该只是更改配置文件的一种情况。
回答by user444904
There is another option DailyRollingFileAppender. but it lacks the auto delete (keep 7 days log) feature you looking for
还有另一个选项DailyRollingFileAppender。但它缺少您正在寻找的自动删除(保留 7 天日志)功能
sample
样本
log4j.appender.DRF=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRF.File=example.log
log4j.appender.DRF.DatePattern='.'yyyy-MM-dd
I do come across something call org.apache.log4j.CompositeRollingAppender, which is combine both the features of the RollingFileAppender(maxSizeRollBackups, no. of backup file) and DailyRollingFileAppender(roll by day).
我确实遇到了一个叫做org.apache.log4j.CompositeRollingAppender 的东西,它结合了RollingFileAppender(maxSizeRollBackups,备份文件数量)和DailyRollingFileAppender(按天滚动)的特性。
But have not tried that out, seems is not the standard 1.2 branch log4j feature.
但是没有尝试过,似乎不是标准的 1.2 分支 log4j 功能。
回答by emory
If you are using Linux, you can configure a cron job using tmpwatch.
如果您使用的是 Linux,则可以使用 tmpwatch 配置 cron 作业。
Most Linux systems have a tmpwatch cron job that cleans up the /tmp directory. You can add another that monitors your logging directory and deletes files over 7 days old.
大多数 Linux 系统都有一个 tmpwatch cron 作业来清理 /tmp 目录。您可以添加另一个监控日志目录并删除超过 7 天的文件。
If you are using a different system, there are probably equivalent utilities.
如果您使用不同的系统,则可能有等效的实用程序。
回答by Al Foltran
The class DailyRollingFileAppender
uses the DatePatternoption to specify the rolling schedule. This pattern should follow the SimpleDateFormat
conventions from Std. Ed. v1.4.2. So, we have to use E
option (Day in week). For example:
该类DailyRollingFileAppender
使用DatePattern选项来指定滚动计划。这种模式应该遵循Std的SimpleDateFormat
约定。埃德。v1.4.2。所以,我们必须使用E
选项(星期几)。例如:
<param name="DatePattern" value="'.'EEE"/>
See more about DailyRollingFileAppender
class from log4j
javadochere. Unfortunately the Java 1.4.2 documentation is no longer online, but you can download a copy here.
在此处DailyRollingFileAppender
从log4j
javadoc 中查看有关类的更多信息。不幸的是,Java 1.4.2 文档不再在线,但您可以在此处下载副本。
回答by Martin Riedel
I create this Methode and call it by closing the application:
我创建了这个 Methode 并通过关闭应用程序来调用它:
public void deleteFiles(){
File f = new File("log");
File[] fileArray = f.listFiles();
double timenow = System.currentTimeMillis();
double olderTenDays = timenow - 864000000;// MS for ten days
for (int i = 0; i < fileArray.length; i++) {
if(fileArray[i].lastModified()< olderTenDays )
fileArray[i].delete();
}
}
回答by Tim Overly
I came across this appender herethat does what you want, it can be configured to keep a specific number of files that have been rolled over by date.
我在这里遇到了这个 appender ,它可以满足您的需求,它可以配置为保留特定数量的按日期滚动的文件。
Download: http://www.simonsite.org.uk/download.htm
下载:http: //www.simonsite.org.uk/download.htm
Example (groovy):
示例(常规):
new TimeAndSizeRollingAppender(name: 'timeAndSizeRollingAppender',
file: 'logs/app.log', datePattern: '.yyyy-MM-dd',
maxRollFileCount: 7, compressionAlgorithm: 'GZ',
compressionMinQueueSize: 2,
layout: pattern(conversionPattern: "%d [%t] %-5p %c{2} %x - %m%n"))
回答by user835745
I had set:
我已经设置:
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.DatePattern='.'yyyy-MM-dd # Archive log files (Keep one year of daily files) log4j.appender.R.MaxBackupIndex=367
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.DatePattern='.'yyyy-MM-dd # Archive log files (Keep one year of daily files) log4j.appender.R.MaxBackupIndex=367
Like others before me, the DEBUG option showed me the error:
像我之前的其他人一样,DEBUG 选项向我显示了错误:
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
log4j:WARN 在 org.apache.log4j.DailyRollingFileAppender 中没有这样的属性 [maxBackupIndex]。
Here is an idea I have not tried yet, suppose I set the DatePattern such that the files overwrite each other after the required time period. To retain a year's worth I could try setting:
这是一个我还没有尝试过的想法,假设我设置了 DatePattern 以便文件在所需的时间段后相互覆盖。为了保留一年的价值,我可以尝试设置:
log4j.appender.R.DatePattern='.'MM-dd
log4j.appender.R.DatePattern='.'MM-dd
Would it work or would it cause an error ? Like that it will take a year to find out, I could try:
它会起作用还是会导致错误?像那样需要一年的时间才能找到,我可以尝试:
log4j.appender.R.DatePattern='.'dd
log4j.appender.R.DatePattern='.'dd
but it will still take a month to find out.
但还需要一个月的时间才能找到答案。