我认为我们不能在 JDBC appender 中使用 DriverManager。您需要使用 JNDI 名称获取连接或创建具有返回连接对象的静态方法的 connectionFactory 类。
以下链接将为您提供帮助。
http://logging.apache.org/log4j/2.x/manual/appenders.html#JDBCAppender
这是您修改后的代码,我认为它应该可以工作。
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error">
<appenders>
<Jdbc name="databaseAppender" tableName="application_log">
<ConnectionFactory class="net.example.db.ConnectionFactory" method="getDatabaseConnection" />
<Column name="level" pattern="%level" />
<Column name="logger" pattern="%logger" />
<Column name="message" pattern="%message" />
</Jdbc>
</appenders>
<loggers>
<root level="warn">
<appender-ref ref="databaseAppender"/>
</root>
</loggers>
</configuration
这是 ConnectionFactory.java 代码。您需要根据您的数据库更改用户、通行证和连接。
package net.example.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnection;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
public class ConnectionFactory {
private static interface Singleton {
final ConnectionFactory INSTANCE = new ConnectionFactory();
}
private final DataSource dataSource;
private ConnectionFactory() {
Properties properties = new Properties();
properties.setProperty("user", "logging");
properties.setProperty("password", "abc123"); // or get properties from some configuration file
GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>();
DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
"jdbc:mysql://example.org:3306/exampleDb", properties
);
new PoolableConnectionFactory(
connectionFactory, pool, null, "SELECT 1", 3, false, false, Connection.TRANSACTION_READ_COMMITTED
);
this.dataSource = new PoolingDataSource(pool);
}
public static Connection getDatabaseConnection() throws SQLException {
return Singleton.INSTANCE.dataSource.getConnection();
}
}
这对我有用。它也应该对你有用。