企业项目管理、ORK、研发管理与敏捷开发工具平台

网站首页 > 精选文章 正文

Spring Boot中自定义appender实现往数据库中记录日志?

wudianyun 2025-07-28 00:49:01 精选文章 5 ℃

在之前的分享中我们介绍了如何实现一个自定义的Appender来对输出到控制台的日志进行格式化操作。并且我们也提到了可以通过自定义的Appender来将日志写入到数据库中,下面我们就来展示一下如何通过自定义的Appender来将日志写入到数据库中。

自定义Appender

我们定义了一个DatabaseAppender的自定义日志处理类,来完成日志写入数据库的操作。

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.db.DBAppenderBase;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseAppender extends DBAppenderBase<ILoggingEvent> {

    protected void subAppend(ILoggingEvent event, Connection connection, PreparedStatement statement) throws Throwable {
        statement.setString(1, event.getLevel().toString());
        statement.setString(2, event.getLoggerName());
        statement.setString(3, event.getMessage());
        statement.setLong(4, event.getTimeStamp());
        statement.execute();
    }

    @Override
    protected void append(ILoggingEvent eventObject) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = connectionSource.getConnection();
            String sql = "INSERT INTO log_table (level, logger, message, timestamp) VALUES (?, ?, ?, ?)";
            statement = connection.prepareStatement(sql);
            subAppend(eventObject, connection, statement);
        } catch (SQLException e) {
            addError("Failed to insert log entry into database.", e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    // Ignore
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // Ignore
                }
            }
        }
    }
}

在上面的例子中,我们创建了一个DatabaseAppender类继承了Logback的DBAppenderBase类,然后再其subAppender()方法中定义了将日志操作事件插入到数据库中的操作逻辑,并且在append()方法中,将日志插入到了数据库中。

配置Logback

完成自定义的Appender添加之后,接下来需要做的事情就是在配置文件中添加Logback的配置来使用这个自定义的Appender来进行日志的写入操作。如下所示。

<configuration>
    <!-- 定义自定义的 Appender -->
    <appender name="databaseAppender" class="com.example.DatabaseAppender">
        <!-- 设置数据源 -->
        <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
            <dataSource class="com.mysql.cj.jdbc.MysqlDataSource">
                <url>jdbc:mysql://localhost:3306/logdb</url>
                <user>username</user>
                <password>password</password>
            </dataSource>
        </connectionSource>
    </appender>

    <!-- 将自定义的 Appender 添加到根日志记录器 -->
    <root level="INFO">
        <appender-ref ref="databaseAppender"/>
    </root>
</configuration>

在上面的配置中我们定义了一个databaseAppender的日志处理器,并且添加了数据源的连接信息,然后通过root节点将日志处理器添加到了处理逻辑中。

总结

完成上面的操作之后,我们就可以将日志记录到Logback中了,当然我们也可以根据具体的需求来对日志记录器Appender来进行优化,例如增加错误信息的处理,对于数据库中不支持的数据类型进行适配等等,或者是通过异步处理的操作来提升日志处理的性能。

最近发表
标签列表