Util logging doesn't delete old log files on rotation

随声附和 提交于 2019-12-12 05:42:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!