5

当我运行以下简单的 log4J 示例时,出现错误:

import org.apache.logging.log4j.core.*;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(
                      log4jExample.class.getName());

  public static void main(String[] args)
                throws IOException,SQLException{

     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
  }
}

错误内容如下:

Error: package org.apache.logging.log4j.core does not exist
Error: cannot find symbol
  symbol:   class Logger
  location: class log4jExample
File: C:\Users\adel\Desktop\various_topics\JavaProjects\log4jExample.java  [line: 10]
Error: cannot find symbol
  symbol:   variable Logger
  location: class log4jExample

所以我相信我正确地将log4J添加到了类路径中,如下所示:

在此处输入图像描述

我从 apache 目录中提取了jar文件,如下所示:log4j-core-2.0-beta4.jar

在此处输入图像描述

我不确定发生了什么——import 语句是如何工作的?即网上的例子告诉我说:

import org.apache.log4j.Logger;

但是如果我的目录结构是这样的:

\apache-log4j-2.0-beta4-bin\org\apache\logging\log4j\core\Logger.java

我是不是不得不说:

import org.apache.logging.log4j.core.Logger;

反而?

4

2 回答 2

11

I think you need both the API and the Core jars in your classpath. Follow these instructions for build and install and these for configuration. On the configuration page, the import line you're asking about is import org.apache.logging.log4j.Logger;, so the Logger class will be pulled from the API jar.

Log4j 2 needs two jars (as opposed to Log4j 1.x which needed one) because of the:

API Separation

The API for Log4j is separate from the implementation making it clear for application developers which classes and methods they can use while ensuring forward compatibility. This allows the Log4j team to improve the implementation safely and in a compatible manner.

于 2013-04-29T04:52:33.230 回答
0

By the way, log4j 2.0 beta5 has some new features that you may be interested in, like Async Loggers, JSP tag library and JMX support.

于 2013-04-29T12:39:01.007 回答