Java日志管理之logback

只要引入logback的依赖,就可以在控制台使用默认格式输出:

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

 在resourses中创建logback.xml配置文件,就可以配置日志:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--定义一个向控制台输出的追加器-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!--
                %thread:线程名字
                %d:产生日志时间
                %level:产生日志的级别
                %logger{10}:由那个类产生的日志,如果超过10个长度则进行缩写
            -->
            <pattern>[%thread] %d %level %logger{10} - %msg%n</pattern>
        </encoder>
    </appender>
    <!--日志的最低输出级别为debug,输出地址为控制台-->
    <root level="debug">
        <appender-ref ref="console"/>
    </root>
</configuration>

如果想配置日滚动文件,可以添加如下追加器:

<!--RollingFileAppender追加器用于生成按天滚动的日志文件-->
<appender name="accessHistoryLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <!--rollingPolicy滚动策略,TimeBasedRollingPolicy按照时间进行滚动-->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!--配置日志存储路径-->
        <fileNamePattern>C:\java_study\project\restful\log\restful.%d.log</fileNamePattern>
    </rollingPolicy>
    <!--定义日志输出的格式-->
    <encoder>
        <pattern>[%thread] %d %level %logger{10} - %msg%n</pattern>
    </encoder>
</appender>

<!--AccessHistoryInterceptor这个类所产生的日志都会使用下面标签所产生的规则-->
<!--additivity是否向控制台输出,false在只会向指定规则下输出-->
<logger name="com.ikidana.restful.interceptor.AccessHistoryInterceptor" level="info" additivity="false">
    <appender-ref ref="accessHistoryLog"/>
</logger>

然后就可以填入信息了:

public class AccessHistoryInterceptor implements HandlerInterceptor {
    //创建一个logger日志对象
    private Logger logger = (Logger) LoggerFactory.getLogger(AccessHistoryInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuilder log = new StringBuilder();
        log.append(request.getRemoteAddr());  //地址
        log.append("|");
        log.append(request.getRequestURL());  //URL
        log.append("|");
        log.append(request.getHeader("user-agent"));
        logger.info(log.toString());
        return true;
    }
}

 

posted @ 2020-03-18 17:13  明王不动心  阅读(515)  评论(0编辑  收藏  举报