需要的包
gradle,版本自选,commons-logging不排除也行,网上有文档说要排除,我这里排不排除都没有关系
compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3' compile group: 'org.logback-extensions', name: 'logback-ext-spring', version: '0.1.2' compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.12' configurations { //compile.exclude module: 'commons-logging' }
maven
<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>
web.xml中增加配置
<context-param> <param-name>logbackConfigLocation</param-name> <param-value>/WEB-INF/config/logback3.xml</param-value> </context-param>
这里的param-value自己定义,我这里是把配置文件放在/WEB-INF/config/目录下,有文档将其放在classpath里,也没差.
logback3.xml里的内容
<?xml version="1.0" encoding="UTF-8"?> <configuration> <timestamp key="bySecond" datePattern="yyyyMMdd"/> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${catalina.base}/logs/weblearn/weblearn3-${bySecond}.log</file> <encoder><!-- 必须指定,否则不会往文件输出内容 --> <pattern>%date %level %thread %10logger %file %line %msg %n</pattern> </encoder> <append>true</append> <prudent>false</prudent> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <!-- <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> --> <pattern>%date %level %thread %10logger %file %line %msg %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> <appender-ref ref="STDOUT" /> </root> </configuration>
这里有很多配置选项,具体的看官方的文档logback配置官方文档
http://logback.qos.ch/manual/appenders.html
我的配置是把日志放在tomcat的日志目录下,C:\apache-tomcat-8.0.32\logs\weblearn\
同时在文件和控制台输出,所以定义了两个<appender></appender>
每天一个日志,
服务器启动后,结果如下
在代码中使用的方法如下
package com.example.weblearn3.controller; import java.io.PrintWriter; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping({"/", "/homepage","index.html"}) public class HomeController { private Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping(method = RequestMethod.GET) public String home() { try { int a = 1/0; }catch (Exception e){ StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); logger.error("Main错误:" + sw.toString()); } System.out.println("home"); return "home"; } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。