您好,登錄后才能下訂單哦!
需要的包
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。