如何在Log4j中根据时间而不是大小来旋转日志文件? [英] How to rotate log files based on time rather than size in Log4j?
问题描述
我使用Log4j和 RollingFileAppender
根据大小创建日志轮换。
I use Log4j with the RollingFileAppender
to create a log rotation based on size.
我如何配置它在旋转之前记录每个文件一定量的时间?
How can I configure it to log to each file for a certain amount of time before rotating?
例如,这样每个日志文件包含一小时的日志,在每小时的顶部旋转?
For example, so that each log file contains one hour of logs, rotating at the top of each hour?
我使用属性
对象以编程方式在Java中配置Log4j(而不是 log4j .properties
file)
I configure Log4j programatically in Java using a Properties
object (as opposed to a log4j.properties
file)
推荐答案
您可能想要使用 DailyRollingFileAppender 。例如,要按小时滚动它们,您将使用'的DatePattern。'yyyy-MM-dd-HH
。对于log4j.properties文件:
You probably want to use a DailyRollingFileAppender. To roll them hourly, for example, you'd use a DatePattern of '.'yyyy-MM-dd-HH
. For a log4j.properties file:
log4j.appender.myAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myAppender.DatePattern='.'yyyy-MM-dd-HH
...
或者对于您的程序化配置:
Or for your programmatic configuration:
DailyRollingFileAppender appender = new DailyRollingFileAppender();
appender.setDatePattern("'.'yyyy-MM-dd-HH");
Logger root = Logger.getRootLogger();
root.addAppender(appender);
不幸的是,使用DailyRollingFileAppender意味着你无法限制文件大小 - 如果这样做可能会有问题在给定的滚动期内你有大量的日志。
Unfortunately, using a DailyRollingFileAppender means that you can't limit the file size - this could be problematic if you have tons of logs in the given rolled period.
这篇关于如何在Log4j中根据时间而不是大小来旋转日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!