Home > OS >  How to output long line with FileHandler?
How to output long line with FileHandler?

Time:12-09

For lines that are not too long, FileHandler works fine. But if the line is decently long, it doesn't write anything to the log file. For example here is the code that tries to write a line of 50k characters:

public class LoggerExample {

    private static final Logger LOGGER = Logger.getLogger(LoggerExample.class.getName());
    public static void main(String[] args) throws SecurityException, IOException {
        FileHandler fileHandler = new FileHandler();
        fileHandler.setFormatter(new SimpleFormatter());
        LOGGER.addHandler(fileHandler);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5000; i  ) {
            sb.append("aaaaaaaaaa");
        }
        LOGGER.info(sb.toString());
    }
}

Is there a way to make this work?

CodePudding user response:

The FileHandler has a limit as described in its documentation:

<handler-name>.limit specifies an approximate maximum amount to write (in bytes) to any one file. If this is zero, then there is no limit. (Defaults to no limit).

It states the default as being no limit, but the limit is set by the logging.properties file found in the used JRE/JDK installation directory. On my system, Java 8 or Java 17, this file contains the line

java.util.logging.FileHandler.limit = 50000

setting the limit to 50000.

Possible solutions:

  • set the limit in the constructor of FileHandler, e.g:
new FileHandler("%h/java%u.log", 0, 1);  // using the default file pattern
  • having a different configuration file (logging.properties) with adjusted limit, specified by the java.util.logging.config.file system property.
  • Related