【问题标题】:log4j.properties file not found in project在项目中找不到 log4j.properties 文件
【发布时间】:2021-01-19 10:40:59
【问题描述】:

我在我的项目中使用 Log4j 并尝试运行我的应用程序,但它似乎找不到 log4.properties 文件。

这是我的 Maven 配置:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>log4j.properties</include>
                <include>hibernate.cfg.xml</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <finalName>File-Name</finalName>
                <archive>
                    <manifest>
                        <mainClass>my.main.class</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path>
                    </manifestEntries>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <appendAssemblyId>false</appendAssemblyId>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

这就是我在代码中加载 log4j.properties 文件的方式。

PropertyConfigurator.configure("log4j.properties");

当我尝试运行应用程序时,出现以下错误:

log4j:ERROR 无法读取配置文件 [log4j.properties]。 java.io.FileNotFoundException: log4j.properties(没有这样的文件或目录)

奇怪的是,如果我用 mvn package 打包我的应用程序并打开 jar 文件,我可以看到里面的 log4j.properties 文件。由于我在 pom 文件中声明了资源文件夹,因此我不明白出了什么问题。

编辑:我在项目中添加了我用于 log4j 的依赖项

   <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

log4j.properties 文件位于 src/main/resources 文件夹中

【问题讨论】:

    标签: java maven log4j


    【解决方案1】:

    如果你使用的是log4j 2.X,则配置不同。

    【讨论】:

    • 感谢您的回复。请检查我在问题中的编辑
    • 你试过把配置文件放到src/main/resources吗?将文件放入上述目录后,请尝试不使用PropertyConfigurator.configure("log4j.properties");
    • 它已经在那里了。检查我在编辑中添加的图片
    • 如果不是这样,我真的不知道该怎么做。试试this链接看看是否有帮助
    【解决方案2】:

    原来是这条线导致了错误

    PropertyConfigurator.configure("log4j.properties");
    

    显然,只要在 maven 中设置了 &lt;directory&gt;/src/main/resource&lt;/directory&gt; 并且文件 log4j.properties 文件存在于资源文件夹中,我就可以直接使用 Logger 而无需此行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2013-02-04
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2013-01-31
      相关资源
      最近更新 更多