Shashank Vivek Shashank Vivek - 1 year ago 105
Java Question

How to create directories for Logger files through FileHandler

I am trying to create logs in directories where each directories are created day wise, but fileHandler is not creating directories rather its throwing exception Couldn't get lock for C:\dir_date\Logging.txt (here dir_date is not present and i am trying to create log into this directory). Can i create directories through "fileHandler " ?

FileHandler fileTxt;
fileTxt = new FileHandler("C:\\ff\\Logging.txt");

log4J can create even directories if not present ,isn't this possible through fileHandler ?

Answer Source

The j.u.l.FileHandler can't create directories. According to the API spec, nonexistent directories are and or should be treated as invalid. Which means your logs should appear in the user home directory instead. This described in JDK-6244047: impossible to specify directories to logging FileHandler unless they exist:

Configuration: By default each FileHandler is initialized using the following LogManager configuration properties. If properties are not defined (or have invalid values) then the specified default values are used.

  • java.util.logging.FileHandler.level specifies the default level for the Handler (defaults to Level.ALL).


  • java.util.logging.FileHandler.pattern specifies a pattern for generating the output file name. See below for details. (Defaults to "%h/java%u.log").

Based on the spec wording above, if the "FileHandler.pattern" property specifies an unusable value, then it is invalid. If an invalid value is specified, then the API is supposed to use the default value. In this case "%h/java%u.log" should be used.

If you need to create directories then you can use the LogManager config option or subclass the FileHandler.

See also: JDK-6258319: No exception with FileHandler file has %h, but %h does not exist

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download