为什么我尝试使用 log4j 时出现此错误?

Why I obtain this error when I try to use log4j?

我完全是 log4j 的新手,我遇到了以下问题。

进入一个名为 Mailer 的 class 我以这种方式声明了我的 log4j Logger 对象:

private static final org.apache.log4j.Logger logger = Logger.getLogger(Mailer.class);

然后我将日志记录到 class 构造函数中(以测试记录器是否正常工作),这样:

public Mailer() {
    super();
    logger.debug("LOGGER IN ACTION !!! INTO Mailer CONSTRUCTOR !!!");
    setTimeoper();
}

问题是,当进入 class 构造器时,记录器似乎无法正常工作并且不打印我的消息,而是我收到此记录器错误(进入控制台):

log4j:WARN No appenders could be found for logger (utility.Mailer).
log4j:WARN Please initialize the log4j system properly.

在我的项目中,我有一个 config 包,其中包含 log4j.properties 文件,该文件的内容极简在控制台中显示 DEBUG log4j 语句:

定义控制台附加程序

log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender

# now define the layout for the appender
log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# now map our console appender as a root logger, means all log messages will go to this appender
log4j.rootLogger = DEBUG, consoleAppender

我认为这是正确的,但我从未指定 log4j 必须这样做(我不知道我必须怎么做以及我必须做什么)

我错过了什么?我该如何解决这个问题并正确配置 log4j?

Tnx

log4j documentation 状态

The exact default initialization algorithm is defined as follows:

  1. Setting the log4j.defaultInitOverride system property to any other value then "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.
  5. If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL.

因为您没有指定这样的 属性,log4j 将在类路径的根目录中寻找 log4j.properties。您的属性文件带有 config,因此 log4j 无法找到它。移动它或向系统 属性 提供它的位置。