如何使用Spring Boot应用程序初始化log4j?

时间:2019-11-15 06:57:46

标签: java spring spring-boot log4j2

我有一个Spring Boot应用程序,我想在此应用程序中使用log4j。问题是我有一个JDBC附加程序,例如(log4j2.xml);

<JDBC name="customDBAppender" tableName="mytable">
    <ConnectionFactory
                class="com.example.logger.ConnectionFactory" method="getConnection" />
    ....
</JDBC>

我有一个静态的getConnection方法,并且需要使用此方法访问我的数据库属性(用户名,密码)。

我认为log4j使用反射来创建与此方法的连接(甚至在Spring Context初始化之前),因此我无法使用Spring注入数据库属性。有什么方法可以注入此属性吗?

我的ConnectionFactory类;

public class ConnectionFactory {

    public static Connection getConnection() throws SQLException {
        Connection connection = new Connection("dbusername", "dbpassword".....)
        ....
    }

}

1 个答案:

答案 0 :(得分:1)

就像您猜到的那样,您无法以这种方式配置jdbc-appender。 相反,您需要从log4j2配置中删除jdbc附加程序,并在Bean中实用地创建它。例如,在@Configuration bean中。

还请注意,即使这样可以工作,也应该始终使用连接池而不是单个连接池,否则会降低应用程序的性能。

执行以下操作:

@Configuration
public class JdbcAppenderConfiguration {
    @Autowired
    private DataSource dataSource;

    //Or @PostConstruct
    @EventListener
    public void handleContextStart(ContextStartedEvent cse) {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        ColumnConfig[] cc = {
            ColumnConfig.createColumnConfig(config, "date", null, null, "true", null, null),
            ColumnConfig.createColumnConfig(config, "level", "%level", null, null, null, null),
            ColumnConfig.createColumnConfig(config, "logger", "%logger", null, null, null, null),
            ColumnConfig.createColumnConfig(config, "message", "%message", null, null, null, null),
            ColumnConfig.createColumnConfig(config, "throwable", "%ex{short}", null, null, null, null),
            ColumnConfig.createColumnConfig(config, "salarie_id", "%X{SALARIE_ID}", null, null, null, null)
        } ;     
        Appender appender = JdbcAppender.createAppender("databaseAppender", "true", null, new Connect(dataSource), "0", "sicdb.bo_log", cc);
        appender.start();
        config.addAppender(appender);
        LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        loggerConfig.addAppender(appender, null, null);
        ctx.updateLoggers();
    }
}
相关问题