1

前言

SpringBoot是一个全家桶,可以方便的集成各种开发工具。日志框架是一个在线应用必需的,本文介绍了当前主流日志框架Logback与SpringBoot的集成方法

准备工作

完成SpringBoot 1024行代码 - Getting Started(一个简单的web应用)

具体步骤

1. 添加Logback的配置文件logback-springboot.xml

其中文件名需要为logback-${name_you_like}.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">

    <contextName>logback</contextName>
    <property name="log.path" value="log/info.log"/>

    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>log/info.log.%d{yyyy-MM-dd}</fileNamePattern>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36}:%line - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="file"/>
    </root>

</configuration>

2. 指定配置文件的位置

在application.properties文件中添加如下一行

logging.config=classpath:logback-springboot.xml

当然也可以把文件名改成logback-${name_you_like}.xml

3. 创建一个测试类Controller

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LogTestController {

    protected final static Logger logger = LoggerFactory.getLogger(LogTestController.class);

    @RequestMapping("/log")
    String log() {
        logger.info("Hello SpringBoot Logback!!");
        return "ok";
    }

}

4. 启动Web应用

5. 测试日志功能

curl 127.0.0.1:8080/log

在info.log文件中看到如下输出

16:33:01.353 logback [http-nio-8080-exec-1] INFO c.e.d.controller.LogTestController:23 - Hello SpringBoot Logback!!

源码

https://github.com/gzllol/spr...


gzlwow
32 声望4 粉丝