问题描述
我有一个Spring Boot应用程序,我想在此应用程序中使用log4j.问题是我有一个JDBC附加程序,如(log4j2.xml);
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>
我有一个静态的getConnection方法,并且需要使用此方法访问我的数据库属性(用户名,密码).
I got a static getConnection method and I need to reach my database properties(username, password) in this method.
我认为log4j使用反射来创建与此方法的连接(甚至在Spring Context初始化之前),因此我无法使用Spring注入数据库属性.有什么方法可以注入此属性吗?
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?
我的ConnectionFactory类;
My ConnectionFactory class;
public class ConnectionFactory {
public static Connection getConnection() throws SQLException {
Connection connection = new Connection("dbusername", "dbpassword".....)
....
}
}
推荐答案
就像您猜到的那样,您无法以这种方式配置jdbc-appender.相反,您需要从log4j2配置中删除jdbc附加程序,并在Bean中实用地创建它.例如,在 @Configuration
bean中.
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.
执行以下操作:
@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();
}
}
这篇关于如何使用Spring Boot应用程序初始化log4j?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!