How to initialize log4j with Spring Boot application?

落花浮王杯 提交于 2021-02-08 10:32:56

问题


I have a Spring Boot application and I want to use log4j with this application. Problem is I have a JDBC appender like(log4j2.xml);

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

I got a static getConnection method and I need to reach my database properties(username, password) in this method.

I think log4j uses reflection to create connection with this method(and even before Spring Context initialization) so I couldn't inject my database properties with Spring. Is there any way to inject this properties?

My ConnectionFactory class;

public class ConnectionFactory {

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

}

回答1:


Like you've guessed, You cannot configure your jdbc-appender this way. Instead you need to remove the jdbc appender from the log4j2 configuration and create it pragmatically in a Bean. For example in a @Configuration bean.

Also please note that even if that'd work this way, you should always use a connection pool instead of a single one otherwise it really degrades your apps performance.

So do as following:

@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();
    }
}


来源:https://stackoverflow.com/questions/58871779/how-to-initialize-log4j-with-spring-boot-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!