首页 > 解决方案 > 如何在@SpringBootTest 期间跳过 JdbcAppender?

问题描述

我们正在使用 JdbcAppender 将所有 WARN 和 ERROR 日志记录到数据库中。但是当我们运行 SpringBootTest 类时,我们使用内存数据库进行测试,因此由于 JdbcAppender 无法记录而引发异常。

Caused by: org.h2.jdbc.JdbcSQLException: Table "APPLICATION_LOG" not found; SQL statement: 
INSERT INTO application_log (application_log_id,service_id,logger,log_level,message,throwable,log_date) VALUES (?,?,?,?,?,?,?)

2018-06-15 11:53:38,369 main ERROR An exception occurred processing Appender DB org.apache.logging.log4j.core.appender.AppenderLoggingException: Cannot write logging event or flush buffer; JDBC manager cannot connect to the database.

方法:

@PostConstruct
public void onStartUp() {
    // Create a new connectionSource build from the Spring properties
    LoggerConnectionSource connectionSource = new LoggerConnectionSource(url, userName, password, validationQuery);
    // This is the mapping between the columns in the table and what to
    // insert in it.
    ColumnConfig[] columnConfigs = new ColumnConfig[7];
    columnConfigs[0] = ColumnConfig.createColumnConfig(null, "application_log_id", "0", null, null, null, null);
    columnConfigs[1] = ColumnConfig.createColumnConfig(null, "service_id", "" + serviceId + "", null, null, "false",
            null);
    columnConfigs[2] = ColumnConfig.createColumnConfig(null, "logger", "%logger", null, null, "false", null);
    columnConfigs[3] = ColumnConfig.createColumnConfig(null, "log_level", "%level", null, null, "false", null);
    columnConfigs[4] = ColumnConfig.createColumnConfig(null, "message", "%message", null, null, "false", null);
    columnConfigs[5] = ColumnConfig.createColumnConfig(null, "throwable", "%ex{full}", null, null, "false", null);
    columnConfigs[6] = ColumnConfig.createColumnConfig(null, "log_date", null, null, "true", null, null);

    // filter for the appender to keep only errors
    ThresholdFilter filter = ThresholdFilter.createFilter(appenderLevel, null, null);

    JdbcAppender appender = JdbcAppender.createAppender(appenderName, "true", filter, connectionSource, "1",
            appenderTableName, columnConfigs);
    // start the appender, and this is it...
    appender.start();
    ((Logger) LogManager.getRootLogger()).addAppender(appender);
}

有没有办法在 @SpringBootTest 期间跳过 jdbcAppender ?

标签: spring-bootjunitlog4j2spring-boot-test

解决方案


推荐阅读