Log4j2 XML defines JDBC Appender and passes property from xml config
I have a maven project running with SpringBoot. I have defined a JDBC application and would like to pass jdbc properties from log4j2.xml
Reading Getting properties programmatically from XML Log4j2 config I did:
- PUT log4j2.xml and logsCommons.properties in src / main / resources folder
-
In log4j2.xml
<Configuration status="warn" monitorInterval="30"> <Properties> <Property name="baseDir">${bundle:logsCommons:baseDir}/</Property> </Properties> <Appenders> <JDBC name="jdbcAppender" tableName="event_log"> <ConnectionFactory class="Log4j2CustomConnectionFactory" method="getDatabaseConnection"/> <Column name="dt_event" isEventTimestamp="true" /> .... </JDBC> </Appenders> <Loggers> </Loggers> </Configuration>
-
Use below java code:
import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp2.ConnectionFactory; import org.apache.commons.dbcp2.DriverManagerConnectionFactory; import org.apache.commons.dbcp2.PoolableConnection; import org.apache.commons.dbcp2.PoolableConnectionFactory; import org.apache.commons.dbcp2.PoolingDataSource; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; public class Log4j2CustomConnectionFactory{ private static interface Singleton { final Log4j2CustomConnectionFactoryINSTANCE = new Log4j2CustomConnectionFactory(); } private DataSource dataSource; private Log4j2CustomConnectionFactory() { LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration configuration = context.getConfiguration(); String baseDirVar = configuration.getStrSubstitutor().getVariableResolver().lookup("baseDir"); /* HERE baseDirVar IS NULL */ /* also configuration.getStrSubstitutor().getVariableResolver().lookup("java"); return NULL */ } public static Connection getDatabaseConnection() throws SQLException { return Singleton.INSTANCE.dataSource.getConnection(); } /*..initializing Datasource with properties retrieved from Log4j2.xml.*/ }
-
The debug command
configuration.getStrSubstitutor().getVariableResolver()
returns the Debug window for printing
Could you please help me understand what is wrong with my configuration?
+1
source to share
No one has answered this question yet
See similar questions:
or similar: