springboot实战之整合slf4j日志系统

来源:互联网 发布:威行通淘宝代运营如何 编辑:程序博客网 时间:2024/06/06 14:14

前言

日志系统几乎是每个项目必备的重要组成部分。但logback和log4j二者推荐使用logback,因为logback的效率显著高于log4j,而且logback也是springboot推荐及默认使用的日志系统。

方法

在Spring Boot 中记录日志只需两步:
1、在 src/main/resources 下面创建logback.xml 文件,并按上面讲述的进行配置。
或者使用最简单的方法在 application 配置文件中配置。
2、在Java代码中创建实例,并在需要输出日志的地方使用。

code实现

在src/main/resources新建logback.xml

<?xml version="1.0" encoding="utf-8"?><configuration scan="true" scanPeriod="10 seconds">    <!--控制台日志-->    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">        <encoder>            <pattern>[springboot-slf4j] %d{yyyy-MM-dd HH:mm:ss.SSS} -%5p ${PID:-} [%15.15t] %-40.40logger{39} : %m%n</pattern>            <charset>UTF-8</charset>        </encoder>    </appender>    <root level="info">        <appender-ref ref="console"/>    </root></configuration>
%d{HH:mm:ss.SSS}——日志输出时间%thread——输出日志的进程名字,这在Web应用以及异步任务处理中很有用%-5level——日志级别,并且使用5个字符靠左对齐%m——日志消息%n——平台的换行符

自定义日志

<logger name="org.springframework.web" level="debug"/>

代码

@SpringBootApplicationpublic class SpringBootSlf4jApplication {    private final static Logger _logger = LoggerFactory.getLogger(SpringBootSlf4jApplication.class);    public static void main(String[] args) {        _logger.info("this is springboot main");        SpringApplication.run(SpringBootSlf4jApplication.class,args);    }}

以上运行的效果
这里写图片描述

文件日志

系统日志全部写在一个文件会导致文件越来越大,这时候可以用文件日志来切分控制台日志

<appender name="dailyRollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">    <File>/usr/local/log/app.log</File>    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">        <!-- daily rollover -->        <FileNamePattern>logback.%d{yyyy-MM-dd}.log</FileNamePattern>        <!-- keep 30 days' worth of history -->        <maxHistory>30</maxHistory>    </rollingPolicy>    <encoder>        <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg %n</Pattern>    </encoder></appender>

logback.%d{yyyy-MM-dd}.log定义了日志的切分方式——把每一天的日志归档到一个文件中,30表示只保留最近30天的日志,以防止日志填满整个磁盘空间。同理,可以使用%d{yyyy-MM-dd HH:mm:ss SSS}来定义精确到分的日志切分方式。

历史文章

SpringBoot实战之入门

springboot实战之文章汇总

springboot实战之读取配置文件

springboot实战之整合jsp模版引擎

springboot实战之整合freemarker模版引擎

springboot实战之注册自定义Servlet

springboot实战之注册filter和listener

springboot实战之注册interceptor

原创粉丝点击