Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 271
dev Avatar asked Feb 13 '23 20:02

dev


1 Answers

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"` 
like image 71
cmd Avatar answered Feb 16 '23 08:02

cmd