1. 准备依赖
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.1</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
</dependencyManagement>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-classic</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
            <exclusions>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>

注意:logback的依赖要使用 1.2.3, 其它的版本没有DBAppender。(不清楚为什么)

  1. 在下面的路径下找到sql的脚本文件,在数据库中执行。
    在这里插入图片描述
  2. 创建一个logback-spring.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!--
    debug="true" : 启动状态监听器
    scan="true"  : 当配置文件修改时,自动加载
    scanPeriod="30 seconds" : 30s 扫描一次配置文件看是否有更改,默认:1min
-->
<configuration debug="true" scan="true" scanPeriod="30 seconds">

<!--    引入springboot的默认配置-->
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
<!--    自定义属性-->
    <property name="LOG_FILE_NAME" value="log/my.log"/>

<!--    输出日志到控制台-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder >
            <pattern>%clr(%d{[ yyyy-MM-dd HH:mm:ss.SSS ]}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(===){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}</pattern>
        </encoder>
    </appender>

<!--    输出日志到文件-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_FILE_NAME}</file>
<!--        对日志文件进行归档-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE_NAME}.log-%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
            <maxFileSize>10KB</maxFileSize>
            <maxHistory>1</maxHistory>
            <totalSizeCap>70KB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>

<!--    直接获取数据库连接的方式,将日志输出到数据库-->
    <appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
        <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
            <driverClass>com.mysql.cj.jdbc.Driver</driverClass>
            <url>jdbc:mysql://localhost:3306/my_log?serverTimezone=Asia/Shanghai</url>
            <user>root</user>
            <password>123456</password>
        </connectionSource>
    </appender>

<!--    连接池的方式,将日志输出到数据库-->
    <appender name="DB_CLASSIC_MYSQL" class="ch.qos.logback.classic.db.DBAppender">
        <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
            <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <driverClass>com.mysql.cj.jdbc.Driver</driverClass>
                <jdbcUrl>jdbc:mysql://127.0.0.1:3306/my_log</jdbcUrl>
                <user>root</user>
                <password>123456</password>
            </dataSource>
        </connectionSource>
    </appender>

<!--    输出指定包下的日志,到 文件和数据库-->
    <logger name="com.shi.log" level="trace">
        <appender-ref ref="FILE"/>
        <appender-ref ref="DB_CLASSIC_MYSQL"/>
    </logger>

<!--    输出整个应用下的日志,到 控制台-->
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>
  1. 启动服务,即可在数据库记录日志,因为同时配置了输出日志到文件,在当前项目下,会创建一个log文件夹,下面存放的也有日志信息。

附加 : com.shi.log.LogApp 类,上面有用到,根据自己的情况配置(用于测试)。

logger name=“com.shi.log” level=“trace”

@SpringBootApplication
package com.shi.log;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class LogApp {
    private static final Logger LOGGER= LoggerFactory.getLogger(LogApp.class);
    public static void main(String[] args) {
        SpringApplication.run(LogApp.class,args);
        LOGGER.trace("追踪");
        LOGGER.debug("debug");
        LOGGER.info("信息");
        LOGGER.warn("警告");
        LOGGER.error("错误");
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        StatusPrinter.print(context);
    }
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐