Java Logger: Create file with rotation number + .log as suffix

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 15:07:38

问题


I am using the Java Logger in the java.util.logging package. This is how I create the logger currently:

FileHandler fileHandler = new FileHandler(filePath, 5242880, 5, true);
fileHandler.setFormatter(new java.util.logging.Formatter() {
  @Override
  public String format(LogRecord logRecord) {
    if(logRecord.getLevel() == Level.INFO) {
      return "[INFO  " + createDateTimeLog() + "]  " + logRecord.getMessage() + "\r\n";
    } else if(logRecord.getLevel() == Level.WARNING) {
      return "[WARN  " + createDateTimeLog() + "]  " + logRecord.getMessage() + "\r\n";
    } else if(logRecord.getLevel() == Level.SEVERE) {
      return "[ERROR " + createDateTimeLog() + "]  " + logRecord.getMessage() + "\r\n";
    } else {
      return "[OTHER " + createDateTimeLog() + "]  " + logRecord.getMessage() + "\r\n";
    }
  }
  });
logger.addHandler(fileHandler)

Now when my logger logs, it creates a file with the extention .0,.1,.2 (etc). I would prefer for it to say .0.log, .1.log (etc). I cannot find where I can set this. Any ideas / help would be great.


回答1:


When you construct your fileHandler object, modify filePath to use a pattern. Create a pattern that makes use of the %g component. This component will be replaced at runtime with the generation number to distinguish rotated logs.

Example
To place log file in the system temp directory with form %TEMP%/mylog.1.log, use the following pattern:

`"%t/mylog.%g.log"` 



回答2:


The first argument to the FileHandler is a file pattern described in the top level class documentation. If you pass just a file name without a pattern the FileHandler will have to resort to appending the generation to the file name so it can rotate between the files. If the generations clash due to multiple JVM instances running at the same time the FileHandler can append a unique number to the file name.

Generate a file pattern something like the following:

FileHandler fileHandler = new FileHandler("%hjvm%g.log", 5242880, 5, true);

This will generate files in your home folder named jvm0.log, jvm1.log, jvm2.log, and so on.



来源:https://stackoverflow.com/questions/21704863/java-logger-create-file-with-rotation-number-log-as-suffix

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