java - log4j 在哪里/如何查找 log4j.properties 文件?

标签 java logging log4j

我正在一个简单的测试应用程序中试用 log4j。我在 eclipse 中创建了一个新的 Java 项目并将 log4j JAR (v1.2.16) 添加到我的构建路径中。然后我创建了一个打印 Hello World 的简单类。然后我使用 log4j Logger 类来记录信息消息。当我运行应用程序时,我会看到日志消息,使用我假设的默认附加程序和布局。伟大的。我遇到的问题是添加我自己的配置。这就是我所做的:

创建了一个带有自定义附加程序和日志级别的 log4j.properties 文件,并将其放入 src 文件夹中(编译时将其复制到 bin 文件夹中)。运行应用程序 - 没有变化。

我尝试添加 PropertyConfigurator.configure("log4j.properties")。运行应用程序 - 没有变化。没有错误,但没有变化。

我必须做什么才能让 log4j 加载我的配置文件?

最佳答案

查看手册标题下的 Default Initialization Procedure ,您将在其中找到以下内容:

The exact default initialization algorithm is defined as follows:

  1. Setting the log4j.defaultInitOverride system property to any other value than "false" will cause log4j to skip the default initialization procedure (this procedure).
  2. Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value "log4j.properties".
  3. Attempt to convert the resource variable to a URL.
  4. If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the classpath by calling org.apache.log4j.helpers.Loader.getResource(resource, Logger.class) which returns a URL. Note that the string "log4j.properties" constitutes a malformed URL. See Loader.getResource(java.lang.String) for the list of searched locations.
  5. If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL. The PropertyConfigurator will be used to parse the URL to configure log4j unless the URL ends with the ".xml" extension, in which case the DOMConfigurator will be used. You can optionaly specify a custom configurator. The value of the log4j.configuratorClass system property is taken as the fully qualified class name of your custom configurator. The custom configurator you specify must implement the Configurator interface.

关于java - log4j 在哪里/如何查找 log4j.properties 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2716824/

相关文章:

java - 在 64 位 JRE 中使用 opengl32.DLL?

python - 记录来自 aiohttp 的 http 请求

c - 日志文件作为列表?

java - 获取特定 log4j 函数的类、方法、行号信息的方法

java - SSS 在 org.apache.log4j.helpers.ISO8601DateFormat 中代表什么?

java - 我如何解析我的日期范围然后检查冲突?

java - 如何在 Java 中创建一个值带有连字符的静态枚举?

java - JAX-RS 身份验证过滤器不是通过@Secured 注释触发的

python 记录 : sending StreamHandler to file from command line

java - 如何每天创建新文件夹并在 slf4j 日志中创建文件