Load java.util.logging.config.file for default initialization

安稳与你 提交于 2019-12-30 00:55:06

问题


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?


回答1:


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.




回答2:


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());
}



回答3:


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.



来源:https://stackoverflow.com/questions/805701/load-java-util-logging-config-file-for-default-initialization

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