log4j.properties not working in executable jar

陌路散爱 提交于 2019-12-07 01:02:29

问题


I'm using eclipse and I have placed log4j.properties in the project directory and I access it by calling

PropertyConfigurator.configure("log4j.properties");

this works fine in Eclipse, but when I extract the project as an executable Jar and run it on another machine, I get an error saying that it can't find log4j.properties. What is the solution to this?


回答1:


What's happening

PropertyConfigurator.configure(String) loads and reads a file from the file-system. Your property file is in the project directory, which would be the "current working directory" when you run from eclipse.

Once you've packaged everything up into a jar, and deployed it - only class files and "resources" are placed into the jar. Resources are non-java files that are under your source tree.

After you've copied the jar file to another machine, the properties file is no longer around.

Solutions

Since your properties file isn't a resource, you'll need to move it separately: place a copy of it on the file system (so it can be edited, updated, etc), in your current working directory of your target host/runtime environment.

Consider placing it in some common area of the file system: for example in /tmp/log4j.properties or ~/.myproject/log4j.properties. Your code will have to be adjusted to look for it, accordingly.

Alternative

Copy the properties file into the root of the source tree (/src, be default). It should then be packaged in the jar. Load the data in the jar file as a resource: PropertyConfigurator.configure(getClass().getResourceAsStream()).

In this case, you can't simply edit the file to adjust your logging preferences.

Many times logic will be written to determine if a properties file is on the file system, and if not then load a default from the jar via this mechanism.




回答2:


PropertyConfigurator.configure(ABC.class.getResourceAsStream("log4j.properties")) 

Worked me correctly, but basically you need to place Log4j properties file in the source code folder (next to Java Class) or you can try putting outside and give proper path in getResourceAsStream() method



来源:https://stackoverflow.com/questions/11919126/log4j-properties-not-working-in-executable-jar

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