Logback日志记录不起作用 [英] Logback logging not working
问题描述
我有一个使用Maven构建的Spring MVC简单地址簿项目.我想使用Logback进行日志记录,但是我是一个新手. 首先,我以这种方式更改了pom.xml:
I've a Spring MVC simple addressbook project build with maven. I want to use Logback for logging, but I'm completely new to it; first I changed my pom.xml this way:
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<exclusions>
<!--Exclude Commons Logging in favor of SLF4j-->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
然后我将以下行添加到我的自定义异常DatabaseException中:
then I added this lines to my custom Exception DatabaseException:
private final static Logger logger = (Logger) LoggerFactory.getLogger(DatabaseException.class);
...
public DatabaseException(Throwable cause) {
super(cause);
logger.log(Level.WARNING, cause.getMessage());
}
所以当我在其他类中出现此异常时,日志可以打印以显示一些消息,但不起作用,当我在Tomcat上运行maven时,它仅打印容器日志[talledContainer] INFO ....等等.似乎我的记录器不存在
so that when I rise in other classes this exception the log is able to print to stout some messages, BUT DOES'T WORK, when I run maven on Tomcat it prints only container log [talledContainer] INFO .... etc etc. seems like my logger doesn't exists
推荐答案
要使您的DatabaseException正常工作,您的DatabaseException应该像这样:
To your DatabaseException make it work, your DatabaseException should be like this:
package org.myorg.myapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatabaseException extends Exception {
private final static Logger logger = LoggerFactory.getLogger(DatabaseException.class);
public DatabaseException(Throwable cause) {
super(cause);
logger.warn(cause.getMessage());
}
}
此外,您需要在pom.xml中包括jcl-over-slf4j依赖项.
Also, you need to include jcl-over-slf4j dependency in your pom.xml.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
我建议阅读参考文档(使用SLF4J部分). http://static.springsource.org /spring/docs/3.2.x/spring-framework-reference/html/overview.html
I would recommend reading the reference documentation (Using SLF4J section). http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/overview.html
希望这会有所帮助.
这篇关于Logback日志记录不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!