这个问题似乎与Using Logback 有关,但 Log4j 开始显示 WARN no Appenders,但那里的答案似乎并没有为我解决这个问题。
当我创建一个除了 slf4j 之外没有依赖项的 maven 项目时,我收到一个警告:
log4j:WARN No appenders could be found for logger (com.example.App).
log4j:WARN Please initialize the log4j system properly.
脚步:
在一个空目录中,执行
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart
Define value for property 'groupId': : com.example
Define value for property 'artifactId': : slf4jtest
Define value for property 'version': 1.0-SNAPSHOT: :
Define value for property 'package': com.example: :
将 SLF4J 添加到 pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>slf4jtest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>slf4jtest</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies>
</project>
在 App.java 中调用记录器
package com.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Logger logger = LoggerFactory.getLogger(App.class);
logger.debug("hello");
System.out.println( "Hello World!" );
}
}
执行:
mvn package
执行:
mvn exec:java -Dexec.mainClass="com.example.App"
输出:
log4j:WARN No appenders could be found for logger (com.example.App).
log4j:WARN Please initialize the log4j system properly.
Hello World!
log4j 未列为依赖项:
$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building slf4jtest 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ slf4jtest ---
[INFO] com.example:slf4jtest:jar:1.0-SNAPSHOT
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] \- org.slf4j:slf4j-api:jar:1.7.2:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.872s
[INFO] Finished at: Tue Feb 19 11:23:33 EST 2013
[INFO] Final Memory: 5M/81M
[INFO] ------------------------------------------------------------------------