Thursday, June 9, 2011

How to append timestamp at end of the log4j.jar related log files, along with RollingFileAppender....?

Configure the following entry in properties file: -

log4j.appender.R=org.apache.log4j.MyDateRollingFileAppender

Compile the following program in log4j.jar folder and add the same class file to classpath: -
//  Compatible with  log4j.jar   1.0.4


package org.apache.log4j;

import java.io.File;
import java.io.FilenameFilter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 *  Referenced classes of package org.apache.log4j:
 */
/**
 * RollingFileAppender, Layout
 */
public class MyDateRollingFileAppender extends RollingFileAppender {

public MyDateRollingFileAppender() {
}

/**
* @deprecated Method MyDateRollingFileAppender is deprecated
*/

public MyDateRollingFileAppender(Layout layout, OutputStream outputstream) {
super(layout, outputstream);
}

/**
* @deprecated Method MyDateRollingFileAppender is deprecated
*/

public MyDateRollingFileAppender(Layout layout, Writer writer) {
super(layout, writer);
}

public MyDateRollingFileAppender(Layout layout, String s, boolean flag)
throws IOException {
super(layout, s, flag);
}

public MyDateRollingFileAppender(Layout layout, String s)
throws IOException {

super(layout, s);
}


    /**
* It rollsOver each time after exceeding the MaxFileSize limit by appending
* the current time stamp to the new Log file
*
* @return void
*/
public synchronized void rollOver() { // rollOver() method has been
// overridden for customized
// functionality


try {

if (maxBackupIndex > 0) {

File[] listOfFiles = locateFile(super.fileName);

/**
* checking the condition to delete the oldest/last log file
*/
if ((listOfFiles != null) && (listOfFiles.length > 0)
&& (listOfFiles.length == (maxBackupIndex + 1))) {

File fileToBeDeleted = listOfFiles[listOfFiles.length - 1];

if (fileToBeDeleted.exists()) { // Deletes the Oldest LOG file.

fileToBeDeleted.delete();
}
}

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
String timeNow = dateFormat.format(new Date());

File oldFile = new File(super.fileName);
File newFile = new File(super.fileName + "." + timeNow);

closeWriterIfOurs();

                /**
* checking the condition for renaming the older file prior to
* the new file
*/
if (oldFile.exists()) { // Renames the Current working file from
// store_ext.log to store_ext.log.<TimeStamp>.

oldFile.renameTo(newFile);
}

setFile(super.fileName, false); // Creates the new working file
                           // for logging purpose.
}
} catch (Exception ex) {

System.out.println(ex.toString());
ex.printStackTrace();
}

}

/**
* locateFile groups the log file and sort based on the descending order of
* timeStamp
*
* @param strFileNameWithPath
* @return fileNames
*/

public File[] locateFile(String strFileNameWithPath) throws Exception {

File extractFile = new File(strFileNameWithPath); // Actual File
final String FILE_NAME = extractFile.getName();

/**
* create a FilenameFilter and override its accept-method
*/
FilenameFilter filefilter = new FilenameFilter() {

public boolean accept(File dirName, String fileName) {

/**
* if the file starts with file name return true, else false
*
*/
return fileName.startsWith(FILE_NAME); // To get list of files
// starts with specific  FILE_NAME
}
};

File fileNameWithPath = new File(strFileNameWithPath);
File dirName = fileNameWithPath.getParentFile();
File[] fileNames = null;

if (dirName.isDirectory()) {

/**
* Get the list of files in the directory.
*/

fileNames = dirName.listFiles(filefilter);
/**
* Sort the files in the array, based on filter.
*/
Arrays.sort(fileNames, new Comparator() {
public int compare(final Object o1, final Object o2) {
return new Long(((File) o2).lastModified())
.compareTo(new Long(((File) o1).lastModified()));
}
});

}
return (fileNames);
}
}