log4j.properties不能在可执行jar中工作 [英] log4j.properties not working in executable jar

查看:218
本文介绍了log4j.properties不能在可执行jar中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用eclipse,我已经将log4j.properties放在项目目录中,并通过调用

  PropertyConfigurator .configure( log4j.properties); 

这在Eclipse中工作正常,但是当我将项目提取为可执行文件Jar并在另一个上运行时机器,我收到一个错误,说它找不到log4j.properties。这是什么解决方案?

解决方案

发生了什么事



code> PropertyConfigurator.configure(String)从文件系统加载和读取文件。您的属性文件位于项目目录中,当您从eclipse运行时,它将是当前工作目录。



将所有内容打包成一个jar后,并部署它 - 只有类文件和资源被放置到jar中。资源是源代码树下的非Java文件。



将jar文件复制到另一台机器后,属性文件不再在。 p>

解决方案



由于您的属性文件不是资源,您需要单独移动:放置一个在您的目标主机/运行时环境的当前工作目录中的文件系统上(因此可以编辑,更新等)的副本。



考虑将其放置在文件系统的某些公共区域:例如/tmp/log4j.properties或〜/ .myproject / log4j.properties。
您的代码将不得不进行调整,以便查找。



替代方案



复制将属性文件放入源代码树的根目录(/ src,默认)。然后将其包装在罐中。将数据作为资源加载到jar文件中: PropertyConfigurator.configure(getClass()。getResourceAsStream())



在这种情况下,您不能简单地编辑文件来调整日志偏好设置。



很多时候会写入逻辑来确定属性文件是否在文件系统,如果没有,则通过此机制从jar加载默认值。


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?

解决方案

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.

这篇关于log4j.properties不能在可执行jar中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆