一、使用slf4j和logback输出日志到控制台
一、使用slf4j和logback输出日志到控制台
二、使用slf4j和logback输出日志到文件
三、使用slf4j和logback输出日志到文件(滚动)
slf4j是Java的简单日志门面API,很多日志实现都可以与之集成,如JDK logging (java.util.logging), log4j和logback。优点是代码里不会有具体的日志实现类,减少侵入。
与log4j相比,logback具有一些优势,如更好的性能、更少的内存使用、自动重加载配置文件以及过滤功能等。
下面简要介绍下logback的使用:
1. 在pom.xml文件中添加依赖:
<properties> <logback.version>1.0.11</logback.version> <slf4j.api.version>1.7.5</slf4j.api.version> </properties> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.api.version}</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> </dependencies>
<?xml version="1.0" encoding="UTF-8"?><configuration> <appender name="STDOUT" level="INFO"> <appender-ref ref="STDOUT" /> </logger> <!-- root的默认level是DEBUG --> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root></configuration>
package com.john.logging.a;public class Reconciliation {private static final Logger log = LoggerFactory.getLogger(Reconciliation.class);public void reconciliate() {String name = "conciliate";log.info("Hello from reconciliate");log.debug("My name is {}", name);}}
package com.john.logging.b;public class Corruption {// logger名称为类的全限定名private static final Logger log = LoggerFactory.getLogger(Corruption.class);public void corrupt() {String name = "allegation";log.info("Hello from corrupt.");log.debug("My name is {}", name);}}
<logger name="com.john.logging.b" level="INFO" additivity="false">