Log4j2 XML define JDBC Appender and pass property

2019-08-07 04:10发布

问题:

i have a maven project runnable with SpringBoot. I defined a JDBC appender and would like to pass jdbc properties from log4j2.xml

Reading Getting properties programmatically from Log4j2 XML config i did:

  1. PUT log4j2.xml and logsCommons.properties in src/main/resources folder
  2. 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>
    
  3. 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.*/
    
    }
    
  4. In debug, instruction configuration.getStrSubstitutor().getVariableResolver() returns Debug Printscreen

Can you please help me to understand what's wrong with my configuration?