I'm trying to create a JDBC appender to log into a DB table. I've succeeded so far by creating a ConnectionFactory and specifying it in log4j2-spring.xml. However, the DB credentials are all hardcoded and I would like to use the credentials I have in my application.yml but since logging seems to be loaded before Spring ApplicationContext, using the @Value annotation doesn't work.
I've also tried building the appender programmatically with this guide as a reference but it's requiring me to define the extended LifeCycle methods in ConnectionSource and I'm not sure what to do with that.
I've tried defining the ConnectionSource class as this but it returns a NullPointerException on this line
Appender jdbcAppender = JdbcAppender.newBuilder()
.setBufferSize(0)
.setColumnConfigs(columnConfigs)
.setColumnMappings()
.setConnectionSource(connectionSource)
.setTableName("LOG")
.setName("databaseAppender")
.setIgnoreExceptions(true)
.setFilter(null)
.build();
This is the ConnectionSource I made:
public class LoggerDatabaseSource implements ConnectionSource
{
private DataSource dataSource;
public LoggerDatabaseSource(String url, String userName, String password, String validationQuery)
{
Properties properties = new Properties();
properties.setProperty("user", userName);
properties.setProperty("password", password);
GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<>();
DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(url, properties);
new PoolableConnectionFactory(cf, pool, null, validationQuery, 3, false, false, Connection.TRANSACTION_READ_COMMITTED);
this.dataSource = new PoolingDataSource(pool);
}
@Override
public Connection getConnection() throws SQLException
{
return dataSource.getConnection();
}
@Override
public State getState() {
return null;
}
@Override
public void initialize() {
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public boolean isStarted() {
return false;
}
@Override
public boolean isStopped() {
return false;
}
}
Any help would be appreciated. Thanks in advance!