当我使用可执行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
文件的类路径中设置了这些JAR包,但还是出现了问题。我编写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
中指定的类路径会覆盖在命令行上指定的任何类路径)。
感谢您的回复,它们肯定帮助我找到了解决错误的正确途径。