spring boot项目中使用sfl4j+logbak配置

1、pom.xml文件

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        

2、配置logback.xml文件,配置目录:/src/main/resources下新增文件logback.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->
    <!--ConsoleAppender,顾名思义是要打印到控制台-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d %p (%file:%line\)- %m%n</pattern>   <!--pattern 配置控制台日志的格式-->
            <charset>UTF-8</charset>   <!--日志的编码格式,UTF-8和我的IDE编码格式一致,不会出现乱码-->
        </encoder>
    </appender>
    <!--RollingFileAppender,顾名思义,是要输出到文件的-->
    <appender name="baselog"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>c:/log/base.log</File><!--千万注意!这里要用绝对路径,我测试了相对路径失败了-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>d:/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>
    <!--日志输出级别,info级别输出到控制台-->
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
    <!--日志输出级别,info级别输出文件-->
 <logger name="com.yzf" level="info"> <appender-ref ref="baselog" /> </logger></configuration>

3、程序中使用sfl4j类

package com.yzf.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {
    private Logger log = LoggerFactory.getLogger(HelloController.class);
    
        /*
         *   http://localhost:8080/hello?name=cn.7player
         */
     
        @RequestMapping("/hello")
        public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
            log.info("hello {}","11111111");
            
            model.addAttribute("name", name);
            return "hello";
        }
}

 

posted @ 2017-07-28 09:29  YaoYiYao  阅读(331)  评论(0编辑  收藏  举报