Log4j2 XML定义JDBC Appender并从xml配置传递属性

时间:2017-10-05 08:58:49

标签: java spring spring-boot log4j2

我有一个可以使用SpringBoot运行的maven项目。 我定义了一个JDBC appender,并希望从log4j2.xml

传递jdbc属性

阅读Getting properties programmatically from Log4j2 XML config我做了:

  1. 在src / main / resources文件夹中输入log4j2.xml和logsCommons.properties
  2. 在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. 使用以下java代码:

    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. 在调试中,指令configuration.getStrSubstitutor().getVariableResolver() 回报 Debug Printscreen

  5. 您能否帮我理解我的配置有什么问题?

0 个答案:

没有答案