只需六步,即可在IDEA的SpringMVC框架中使用slf4j-logback来打印log日志。
第一步:
你需要有一个SpringMVC项目,IDEA自己生成的HelloWorld就可以。另外服务器我用的是Tomcat。
第二步:
在pom.xml中添加如下依赖,IDEA会自动进行下载。
其中,第一个logback-classic包含了基本的jar包,第二个logback-ext-spring包含了LogbackConfigListener,稍后会配置,第三个jcl-over-slf4j的作用是可以看到Spring框架本身打印的日志。
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.logback-extensions</groupId> <artifactId>logback-ext-spring</artifactId> <version>0.1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.12</version> </dependency>
第三步:
新建一个logback.xml,放到resources路径下。其中“com.springapp.mvc”需要换成你自己的java文件所在的包路径。
后面的level是日志显示等级,DEBUG等级最低,可以显示所有level的日志,WARN等级居中,可以显示WARN及其以上level的日志,ERROR等级最高,只能显示ERROR这个level的日志。所以一般用DEBUG就行。
level等级顺序:error>warn>info>debug。
<?xml version="1.0" encoding="UTF-8"?> <!-- For assistance related to logback-translator or configuration --> <!-- files in general, please contact the logback user mailing list --> <!-- at http://www.qos.ch/mailman/listinfo/logback-user --> <!-- --> <!-- For professional support please see --> <!-- http://www.qos.ch/shop/products/professionalSupport --> <!-- --> <configuration> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <Target>System.out</Target> <Encoding>UTF-8</Encoding> <encoder> <pattern>%d{HH:mm:ss.SSS} %5p [%t] [%c{1}]:%L - %m%n</pattern> </encoder> </appender> <appender name="logfile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!--See http://logback.qos.ch/manual/appenders.html#RollingFileAppender--> <!--and http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy--> <!--for further documentation--> <Encoding>UTF-8</Encoding> <encoder> <pattern>%d %p [%t] [%c]:%L - %m%n</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>DEBUG</level> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>log/%d{yyyy-MM-dd-HH‘.log‘}</fileNamePattern> </rollingPolicy> </appender> <logger name="org.springframework" level="WARN"/> <logger name="org.springframework.remoting" level="WARN"/> <logger name="org.springframework.scheduling.quartz" level="WARN"/> <logger name="org.springframework.data.jpa" level="DEBUG"/> <logger name="org.cometd" level="WARN"/> <logger name="ch.qos.logback" level="WARN"/> <logger name="com.springapp.mvc" level="DEBUG"/> <root level="ERROR"> <appender-ref ref="stdout"/> <appender-ref ref="logfile"/> </root> </configuration>
第四步:在web.xml中进行如下配置,包括logback.xml的位置和前面提到的Listener。
<context-param> <param-name>logbackConfigLocation</param-name> <param-value>classpath:/logback.xml</param-value> </context-param> <listener> <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class> </listener>
第五步:在java代码中加入log相关代码,注意以下几点:
1.此处log调用error方法表明此日志等级为ERROR,显示等级最高,即前面配置DEBUG和ERROR的包都可以显示此日志。
2.“int a = 1/0;”是为了测试显示异常日志用。
3.StringWriter和PrintWriter的使用是为了完整显示出异常的详细日志,不是必需的。
/** * Main * * @author 徐飞 * @version 2016/06/22 09:30 */ @Controller @RequestMapping("/") public class MainController { private Logger log = LoggerFactory.getLogger(MainController.class); @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { try { int a = 1/0; }catch (Exception e){ StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error("Main错误:" + sw.toString()); } model.addAttribute("message", "Hello world!"); return "index"; } }
第六步:也是最后一步,运行程序,然后打开项目所用Tomcat中的log文件夹,即可看到打印出来的详细日志“/ by zero”。
参考:http://spring.io/blog/2009/12/04/logging-dependencies-in-spring
spring默认使用了commons-logging,在集成其它日志框架,slf4j使用了编译时绑定来代替运行时发现.它注定是更高效的(当然slf4j还可以使用占位符绑定等功能).下文介绍spring三种常用方案记录日志,推荐第三种
方案一:commons-logging+Log4J
1.依赖:
[html] view plain copy
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
2.在classpath根目录添加log4j.properties或log4j.xml,关于开发的日志级别配置,调得太高,会漏到一些信息看不见,调得太低,输出得太多,看得眼花缭乱,在产品阶段甚至影响应用性能.我觉得开发时,默认(一般依赖也是用默认appender)给WARN,项目本身编写的代码可以给DEBUG,其它另外特别指定,以下是log4j.properties的一个例子:
[plain] view plain copy
- log4j.rootCategory=WARN, stdout
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
- log4j.category.org.exam=DEBUG
- log4j.category.org.springframework.beans.factory=INFO
根据log4j API(http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Category.html),Category已经过时,应使用Logger代替.而Logger是Category的子类,在Category的所有操作都可以在Logger上执行.以上的properties文件内容应改为
[plain] view plain copy
- log4j.rootLogger=WARN, stdout
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
- log4j.logger.org.exam=DEBUG
- log4j.logger.org.springframework.beans.factory=INFO
3.代码用法:
[java] view plain copy
- import org.apache.log4j.Logger;
- public class UserService {
- final Logger logger = Logger.getLogger(UserService.class);
- public boolean save(){
- logger.error("虽然A喜欢我,但是我喜欢B");
- return true;
- }
- }
方案二:slf4j+Log4J
1.先在spring排除commons-logging.再引入4个包:桥接包jcl-over-slf4j,SLF4J API包slf4j-api,绑定到Log4J的包slf4j-log4j12,Log4J实现包log4j12.
[html] view plain copy
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>jcl-over-slf4j</artifactId>
- <version>1.7.7</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.7</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- <exclusions>
- <exclusion>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
2.log4j配置同上.
3.代码用法:
[java] view plain copy
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class UserService {
- final Logger logger = LoggerFactory.getLogger(UserService.class);
- public boolean save(){
- logger.error("虽然{}喜欢我,但是我喜欢{}","A","B");
- return true;
- }
- }
方案三:slf4j+logback.其中,logback是slf4j原生的实现.
1.先引入logback-classic依赖,它会将其它依赖引入,再在spring排除commons-logging.
[html] view plain copy
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>1.1.3</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- <exclusions>
- <exclusion>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
2.logback配置:查找顺序logback.groovy-->logback-test.xml-->logback.xml,详细配置还是参考文档http://logback.qos.ch/documentation.html.下面是logback.xml例子
[html] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>%d{yy.MM.dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
- </encoder>
- </appender>
- <logger name="org.exam" level="debug" />
- <logger name="org.springframework.beans.factory" level="info" />
- <root level="warn">
- <appender-ref ref="console"/>
- </root>
- </configuration>
3.代码用法:同方案二一样