how to append date in log file name , like log_12.12.2012.log?

727 views Asked by At

I know the DailyRollingFileAppender will do it for me.But it does not support the maximum file size when my file size was reached to the specified size.

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">

    <param name="Threshold" value="ALL" />
    <param name="MaxFileSize" value="50KB" />
    <param name="MaxBackupIndex" value="10" />
    <param name="File" value="F:/logs/Testing/MyProject.log" /> 

    <layout class="org.apache.log4j.PatternLayout"> 
          <param name="ConversionPattern" value="%d{MMM-dd-yyyy HH:mm:ss:SSS} %-5p %m%n"/>
    </layout>
</appender>

I want to create my file name to be like MyProject_12.12.2012.log .

My need is ,

  1. My log file will need to support the max file size

  2. Every log file has unique name with date.

Hope our stack users will help me.

1

There are 1 answers

0
Sergey On

There are several implementations available in public space, but actually it is much easier override RollingFileAppender

For example:

public class MyRollingAppender extends RollingFileAppender {

Long nextCheck=System.currentTimeMillis () - 1;
public static final SimpleDateFormat FORMAT=new SimpleDateFormat("yyyyMMdd");
String fileNameOriginal=null;

private void rollFile() {
    this.closeFile();
    GregorianCalendar calendar=new GregorianCalendar();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.add(Calendar.DATE, 1);

    nextCheck=calendar.getTimeInMillis();
    this.setFile(fileNameOriginal);
    this.activateOptions();
}

@Override
protected void subAppend(LoggingEvent event) {
    Long n=System.currentTimeMillis ();
    if (n>nextCheck) {
        rollFile();
    }
    super.subAppend(event);
}

@Override
public void setFile(String file) {
    fileNameOriginal=file;
    super.setFile(file + FORMAT.format(new Date()) +".log");
}

}

You can adjust it to you specific needs