IntelliJ Java IDE
The moose likes I/O and Streams and the fly likes How to limit the size of a log file? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "How to limit the size of a log file?" Watch "How to limit the size of a log file?" New topic
Author

How to limit the size of a log file?

Michael Gavryuchkov
Ranch Hand

Joined: Jan 13, 2002
Posts: 37
My application writes to a log file and (no wonder) the file growing. I don't want it to get too huge.
Are there any ways to remove lines from the beginning of the file? So far I couldn't find any, at least in RandomAccessFile and FileWriter.


SCJP1.4, SCWCD, OCP<br />AppFuse, <a href="http://www.internetpolyglot.com" target="_blank" rel="nofollow">http://www.internetpolyglot.com</a>
Neil Johnson
Greenhorn

Joined: Jan 22, 2002
Posts: 11
Hi, I am not aware of any methods either. I worked around this by creating numbered versions of the log file using an ErrorLogger class. The user can request the server application to close the current version of the log file and open a new one. This would then allow you to archive or delete the old ones. The code for a couple of the methods from this class are attached. The openLogFile method that is used to lookfor the next log file is attached. The logFileprefix is a public variable that sets the path and prefix of the log file. e.g. c:/someplace/LogStuff which with the suffix generates a name of c:/someplace/LogStuff000.log.
You can create your own logMsg method which counts lines, and automatically opens a new log file once your 'limit' has been reached, or on a daily basis, or whatever.
Its not elegant, but I hope it helps.
Neil
/**
* Opens a new log file for logging messages.
* This method will create numbered logfiles in sequence. It takes the logfile prefix and extension
* that it has been given previously, and looks for the highest number logfile in the directory. It then increments
* this number by one and opens a new log file with that number. If a Log File is already open
* it closes the existing file first.
* @return void
* @Exception IOException thrown for usual file-related errors including path not found, etc.
*/
public static void openLogFile() throws IOException {
String versionNumber;
if (currentVersion==0) {
int version;
int versionFnd=0;
File logFile = new File(logFilePrefix);
String prefix = logFile.getName();
int prefixLen = prefix.length();
String parentDir=logFile.getParent();
if (parentDir==null) parentDir = ".";
File dir = new File(parentDir);
// Find highest file version
String logFiles[] = dir.list();
int prefixFnd=0;

if (logFiles!=null) {
for (int ptr = 0;ptr < logFiles.length;ptr++) {
if ((prefixFnd=logFiles[ptr].indexOf(prefix))>=0) {
// The following assumes that the version is always 3 digits
versionNumber = logFiles[ptr].substring(prefixFnd+prefixLen,logFiles[ptr].indexOf("."));
try {
version = Integer.parseInt(versionNumber);
} catch (NumberFormatException e) { version = 0;}
if (version>versionFnd) versionFnd = version;
}
}
} else
versionFnd = 0;
currentVersion = versionFnd; // This is the highest number found
}
if (currentVersion>=999) currentVersion=0; // Wrap at 999
// increment highest version by 1
versionNumber=String.valueOf(++currentVersion);
while (versionNumber.length()<3) { versionNumber = "0" + versionNumber; }
logFile = logFilePrefix + versionNumber + extension;
if (outputStream != null) closeLogFile();
outputStream = new FileOutputStream(logFile);
logToFile = true;
logMsg("Opened log file: " + logFile);
}

/**
* Close the Log file - ignore any errors that occur.
* @return void
*/
public static void closeLogFile() {
try {
logMsg("Closing log file: " + logFile);
logToFile = false;
outputStream.close();
} catch (IOException e) { /* Ignore it */ }
}
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
In this situation, I test the log file length after each new entry. If too long, I rename the log file (e.g. "logger.log") to a backup log file (e.g. "backup.log"), having first deleted any previous backup log file. Then I start writing to a new log file (still called, in the example, "logger.log").
In this way, the maximum amount of log on the disk is twice the maximum size of the log file.
Not the smartest possible solution, but easy.
NB: Watch for Windows lying to you about deleting the backup log file. It will be unable to rename the main log file to the backup name for a short while after deleting previous backup log. Some sort of loop is therefore needed


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Michael Gavryuchkov
Ranch Hand

Joined: Jan 13, 2002
Posts: 37
Thanks for answering. I decided to open a new log file each month (I know for sure the log files won't be too long) and to have yyyyMM postfix in each log file.
 
 
subject: How to limit the size of a log file?
 
Threads others viewed
Eclipse hangs on a redirect from a servlet
unsynchronized file reading
logging of compile time errors
Problem running a simple webapplication in struts
log4j: Reading Log level from DB
MyEclipse, The Clear Choice