【发布时间】:2015-04-18 22:33:43
【问题描述】:
我在使用可执行 JAR 文件时无法指定 Log4j2 配置文件位置。如果我将所有 JAR 分开,它工作正常,但是当我尝试将它们组合成一个可执行 JAR 文件时,由于某种原因,log4j2.xml 文件没有从命令行中提取。
我试过这两种指定位置的方法:
java -Djava.libary.path=..\bin -cp ..\config -jar MyApplication.jar
java -Djava.libary.path=..\bin -Dlog4j.configurationFile=..\config\log4j2.xml -jar MyApplication.jar
这些都不起作用。我还尝试将包含配置文件的目录添加到 JAR 清单文件中的类路径中:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.2
Created-By: 1.7.0_21-b11 (Oracle Corporation)
Main-Class: com.abc.MyApplication
Class-Path: ../config/
这种方法我也没有成功。有什么想法我可能做错了吗?
提前感谢您的帮助!
编辑
啊,我想我弄错了问题。最初,这是我在命令行输出中看到的错误:
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
但是在我更改内容的某个时候,错误消息在我没有意识到的情况下更改为:
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
所以我发现,即使我正在构建的可执行 JAR 在其中包含 log4j-core-2.1.jar 和 log4j-api-2.1.jar JAR 以及在 MANIFEST 文件的类路径中,还是存在问题。我编写我的 ant 文件以将库组合到我正在创建的单个 JAR 中的方式是成功复制目录和类文件,但由于某种原因没有复制其他类型,这显然也是必要的(例如 Log4j-config .xsd、Log4j-events.dtd 等)。
为了解决这个问题,我将在 Ant 构建文件中合并 JAR 的方式更改为:
<jar destfile="${dist}/${jarName}" basedir="${classes}"
excludes=".svn">
<!-- Merge this JAR with all the JARs in the lib directory, so that
we are only creating one distribution JAR that includes all the
libraries that you need. -->
<fileset dir="${classes}" includes="**/*.class" />
<zipgroupfileset dir="${lib}" includes="**/*.jar" />
<!-- Specify the manifest file of the JAR -->
<manifest>
<attribute name="Main-Class" value="com.abc.MyApplication"/>
<attribute name="Class-Path" value=". ${manifest.classpath}"/>
</manifest>
</jar>
这解决了问题并将所有文件从 JAR 复制到我新创建的 JAR 中。
一旦这个问题得到解决,我在上面发布的第二个命令就可以指定配置文件的位置。 (正如下面@rewolf 所指出的,第一个命令将不起作用,因为 JAR 的 MANIFEST 中指定的类路径会覆盖命令行中指定的任何类路径。
感谢您的回复,他们肯定帮助我走上了正确的道路,以找出我的错误。
【问题讨论】:
-
所以你的配置文件不在应用jar里面?
-
不,我认为将配置文件保存在 JAR 之外是一种更好的做法,这样用户可以根据需要更改配置。我需要在 JAR 中包含该文件吗?
-
你如何创建你的单个 jar? log4j2-core jar 包含必须包含的配置文件,否则 log4j2 将无法正常工作。
-
请添加您从 log4j 收到的输出。我假设它是抱怨没有配置文件的默认状态记录器 - 但假设它可能是一个错误
标签: java logging executable-jar log4j2