问题
I used the below code to configure my logging.
public Boolean configureLogPath(String logPath, String level, String logComponents, int logFileSize,
int logFileCount) {
int logFileSizeInKbs = logFileSize * 1000;
Boolean result = false;
String[] splitComponents = logComponents.split(",");
for (String component : splitComponents) {
loggableComponents.add(component);
}
switch (level) {
case "info":
LOGGER.setLevel(Level.INFO);
break;
case "severe":
LOGGER.setLevel(Level.SEVERE);
break;
case "debug":
LOGGER.setLevel(Level.CONFIG);
break;
case "off":
LOGGER.setLevel(Level.OFF);
break;
default:
LOGGER.setLevel(Level.SEVERE);
}
try {
simpleFormatter = new SimpleFormatter();
logFileHandler = new FileHandler(logPath, logFileSizeInKbs, logFileCount);
logFileHandler.setFormatter(simpleFormatter);
LOGGER.setFilter(filter);
LOGGER.addHandler(logFileHandler);
result = true;
} catch (SecurityException e1) {
result = false;
LOGGER.log(Level.SEVERE, "Security exception when reading log file" + e1);
} catch (IOException e1) {
result = false;
LOGGER.log(Level.SEVERE, "IO Exception when reading log file" + e1);
}
return result;
}
But though I have given the relevant parameters in the FileHandler for the logs to be rotated, the old log files still remain. Is this a behavior of util logging or is there anything I can do to remove old files during rotation?
回答1:
Is this a behavior of util logging or is there anything I can do to remove old files during rotation?
Per the FileHandler documentation:
For a rotating set of files, as each file reaches a given size limit, it is closed, rotated out, and a new file opened.
If you want to delete rotated files then simply don't rotate. The goal of rotation is so that you can read old log data.
If you really want to rotate and delete old files you can override the FileHandler.setOutputStream method to listen for the rotation and write your own delete method.
private boolean constructed;
@Override
protected synchronized void setOutputStream(OutputStream out) throws SecurityException {
super.setOutputStream(out);
if (constructed && Level.OFF.equals(super.getLevel())) { //Rotating...
deleteRotatedFiles();
}
constructed = true;
}
来源:https://stackoverflow.com/questions/34409993/util-logging-doesnt-delete-old-log-files-on-rotation