Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

java - How to rotate log files based on time rather than size in Log4j?

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?

I configure Log4j programatically in Java using a Properties object (as opposed to a log4j.properties file)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...