问题
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