我有一个可以使用SpringBoot运行的maven项目。 我定义了一个JDBC appender,并希望从log4j2.xml
传递jdbc属性阅读Getting properties programmatically from Log4j2 XML config我做了:
在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>
使用以下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.*/
}
在调试中,指令configuration.getStrSubstitutor().getVariableResolver()
回报
Debug Printscreen
您能否帮我理解我的配置有什么问题?