在特殊的应用程序事件中,我需要滚动日志文件并重命名为包含日期和时间的特定文件名。
这是我用来滚动文件的功能:
public void rollOver()
{
Enumeration el= Logger.getRootLogger().getAllAppenders();
while ( el.hasMoreElements() )
{
Appender a = (Appender) el.nextElement();
if (a instanceof RollingFileAppender)
{
((RollingFileAppender) a).rollOver();
}
}
}
这是log4j.properties配置:
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=mylog.log
log4j.appender.logfile.Threshold=ALL
log4j.appender.logfile.MaxFileSize=100MB
log4j.appender.logfile.MaxBackupIndex=4
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %-4r [%t] %-5p %c %x - %m%n
目前,在rollOver
我有名称为mylog.log.1
的文件后。如何使文件具有mylog_YYYMMDD_HHmmSS.log
之类的名称?
答案 0 :(得分:1)
使用DailyRollingFileAppender
代替RollingFileAppender
。有关如何配置它的详细信息,请参阅此问题:Setting a log file name to include current date in Log4j
答案 1 :(得分:0)
根据要求
# Log levels
log4j.rootLogger=DEBUG,CONSOLE,R
# Appender Configuration
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.R.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.R.RollingPolicy.FileNamePattern=./logs/file_%d{yyyy-MM-dd}.log
# Layout for Rolling File Appender
#log4j.appender.R.DatePattern='.'yyyy-MM-dd-HH'.log'
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n