我开发了一个应用程序,用于使用 JDBCAppender 使用 log4j2.xml 将记录记录到数据库中。我在这里遵循了以下说明:- http://self-learning-java-tutorial.blogspot.in/2015/10/log4j2-jdbcappender-write-log-messages.html
我的 DB ConnectionFactory 类如下:-
导入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", "sa");
properties.setProperty("password", "Login@123"); // or get properties from some configuration file
GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>();
DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
"jdbc:sqlserver://SERV1-PC\\SQLEXPRESS:1433;databaseName=Anirban;", 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();
}
}
我的 log4j2.xml 片段如下:-
<Appenders>
<JDBC name="databaseAppender" tableName="LogTable">
<ConnectionFactory class="ConnectionFactory" method="getDatabaseConnection" />
<Column name="EVENT_DATE" isEventTimestamp="true" />
<Column name="LEVEL" pattern="%level" />
<Column name="LOGGER" pattern="%logger" />
<Column name="MESSAGE" pattern="%message" />
<Column name="THROWABLE" pattern="%ex{full}" />
</JDBC>
</Appenders>
<AsyncRoot level="INFO" >
<AppenderRef ref="databaseAppender" />
</AsyncRoot>
现在一切正常,我可以看到数据库中的日志。
但是当我将此项目导出为 jar 文件以使其成为公共共享库 jar 并在其他应用程序中作为依赖项使用时,我遇到了 ClassNotFoundException。
因此,每当我启动具有此共享 jar 文件作为依赖项的应用程序时,我都会得到以下信息:-
ERROR java.lang.ClassNotFoundException: ConnectionFactory java.lang.ClassNotFoundException: ConnectionFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
我不确定为什么这个 ConnectionFactory java 类没有进入共享 jar 中的类路径,但是当它作为上述应用程序运行时工作正常。
请建议,如何在jar的类路径中包含ConnectionFactory java类?那么我需要在我的 log4j2.xml 中进行修改吗?