I'm trying to load a custom log.properties
file when my application is started.
My properties file is in the same package as my main class, so I assumed that the -Djava.util.logging.config.file=log.properties
command line parameter should get the properties file loaded.
But the properties are only loaded when i specify a full absolute path to the properties file. Any suggestions how to use a relative path?
Java logging doesn't search your whole hard disk for a file; there are very simple rules how files are looked up. You want Java to see that the two files belong to each other but you didn't say so anywhere. Since Java sees no connection between the properties file and your class other than that they are in the same folder on your disk, it can't find the file.
-Djava.util.logging.config.file=log.properties
only works if the file log.properties
is in the current directory of the Java process (which can be pretty random). So you should use an absolute path here.
An alternate solution would be to move the file logging.properties
into $JAVA_HOME/lib/
(or edit the file which should be there). In that case, you don't need to set a System property.
You can dynamically load java.util.logging
properties files from a relative path very easily. This is what I put inside a static {}
block in my Main
class. Put your logging.properties
file in the default package
and you can access it very easily with the following code.
final InputStream inputStream = Main.class.getResourceAsStream("/logging.properties");
try
{
LogManager.getLogManager().readConfiguration(inputStream);
}
catch (final IOException e)
{
Logger.getAnonymousLogger().severe("Could not load default logging.properties file");
Logger.getAnonymousLogger().severe(e.getMessage());
}
util logging does not load from classpath, it needs an absolute path which is why other logging packages like log4j are far easier to configure and better for web apps where it's a pain to get abs paths.
this is not explained at all in the java.util.logging.LogManager doco.