Java程序,日志输出,我认为是第一位的,把它的应用拿到这里。
Spring-Boot对日志的处理,和我们往常的处理完全可以一致,通过logback.xml进行处理,即使有更先进的东西,我们也不用去管它。
这里,为了简便,我们任然使用前一篇的工程spring-boot-sample-data
第一步,在src/main/resources中增加logback.xml文件,文件内容为(这里仅最简单的,根据工程情况,进行相应的配置):
<pre name="code" class="html"><configuration>
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<charset>GBK</charset>
</encoder>
</appender>
<appender name="baselog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>log/base.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/base.log.%d.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 64 MB -->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<logger name="com.example" level="DEBUG">
<appender-ref ref="baselog" />
</logger>
</configuration>
注:1、控制台和日志文件的字符集
2、日志文件的存放位置,须要遵守linux的命名规则
第二步,改造HelloController文件,改造结果如下
package com.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
protected static Logger logger=LoggerFactory.getLogger(HelloController.class);
@RequestMapping("/")
public String helloworld(){
logger.debug("访问hello");
return "Hello world!";
}
@RequestMapping("/hello/{name}")
public String helloName(@PathVariable String name){
logger.debug("访问helloName,Name={}",name);
return "Hello "+name;
}
}
注:在添加引用时,日志的包一定是org.slf4j.Logger、org.slf4j.LoggerFactory
第三步、测试
1、运行程序
2、在浏览器中依次输入
http://localhost:8080/
http://localhost:8080/hello/上帝3、在工程所在的根目录找到log文件夹,进去,再打开base.log,入下图
注:文件夹和日志文件的名称,都是在配置文件logback.xml中设置的
通过这个实例,我们完全用过去的技术处理日志,暂时不用去管别的,直接使曾经的技术。