springboot运用logback将日志写入数据库

  • A+
所属分类:java

SpringBoot项目中日志写入数据库,最主要的核心类就是DBAppender。

我使用的MySQL数据库,创建auge_log数据库,执行以下内容建表。

BEGIN;
DROP TABLE IF EXISTS logging_event_property;
DROP TABLE IF EXISTS logging_event_exception;
DROP TABLE IF EXISTS logging_event;
COMMIT;
 
BEGIN;
CREATE TABLE logging_event 
  (
    timestmp         BIGINT NOT NULL,
    formatted_message  TEXT NOT NULL,
    logger_name       VARCHAR(254) NOT NULL,
    level_string      VARCHAR(254) NOT NULL,
    thread_name       VARCHAR(254),
    reference_flag    SMALLINT,
    arg0              VARCHAR(254),
    arg1              VARCHAR(254),
    arg2              VARCHAR(254),
    arg3              VARCHAR(254),
    caller_filename   VARCHAR(254) NOT NULL,
    caller_class      VARCHAR(254) NOT NULL,
    caller_method     VARCHAR(254) NOT NULL,
    caller_line       CHAR(4) NOT NULL,
    event_id          BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY
  );
COMMIT;
 
 
BEGIN;
CREATE TABLE logging_event_property
  (
    event_id       BIGINT NOT NULL,
    mapped_key        VARCHAR(254) NOT NULL,
    mapped_value      TEXT,
    PRIMARY KEY(event_id, mapped_key),
    FOREIGN KEY (event_id) REFERENCES logging_event(event_id)
  );
COMMIT;
 
 
BEGIN;
CREATE TABLE logging_event_exception
  (
    event_id         BIGINT NOT NULL,
    i                SMALLINT NOT NULL,
    trace_line       VARCHAR(254) NOT NULL,
    PRIMARY KEY(event_id, i),
    FOREIGN KEY (event_id) REFERENCES logging_event(event_id)
  );
COMMIT;

然后在pom中添加的dbcp的依赖

<dependency>
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
</dependency>

之后在logback.xml中添加写入数据库的配置信息(这里设置了写入数据库的日志级别为error,root日志级别为INFO)

<?xml version="1.0" encoding="UTF-8"?>
 
<configuration debug="false">
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="E:/Code/log" />
    <!--将日志写入文件的配置信息在上节中,本节就不展示了,只展示重点配置-->
    <!-- 彩色日志 -->
    <!-- 按照每天生成日志文件 -->
    <!--info-->
    <!--error appender-->
 
    <!-- 将日志写入数据库 -->
    <appender name="DB-CLASSIC-MYSQL-POOL" class="ch.qos.logback.classic.db.DBAppender">
        <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
            <dataSource class="org.apache.commons.dbcp.BasicDataSource">
                <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                <url>jdbc:mysql://localhost:3306/auge_log?characterEncoding=UTF-8</url>
                <username>root</username>
                <password>123456</password>
            </dataSource>
        </connectionSource>
        <!--这里设置日志级别为error-->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>error</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
 
    <!-- 日志输出级别 TRACE < DEBUG < INFO < WARN < ERROR < FATAL-->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="DAYINFO" />
        <appender-ref ref="DAYERROR" />
        <appender-ref ref="DB-CLASSIC-MYSQL-POOL" />
    </root>
</configuration>

示例:

Logger logger = LoggerFactory.getLogger(UserController.class);
 
@RequestMapping("/login")
@LogApi(info = "用户登陆")
public String login(String loginName, String password, Model model){
    User user = userService.getUserByLogin(loginName,password);
    if(user==null){
      //在此试验是否写入数据库
        logger.error("用户名或密码错误,请重新登录");
        model.addAttribute("emg","用户名或密码错误,请重新登录");
        return "login";
    }
  logger.info("测试info级别是否也能写入数据库");
    session.setAttribute("user",user);
    return "index";
}

查看数据库记录如下:

说明配置成功了(只有error才会写入数据库)

avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: