If you are using mysql. create a file log4j.properties. This worked for me.
Put this at the root folder of you application. i.e root of all packages. I also do have a table logs with fields id,date,user, message and class.
log4j.rootLogger=DEBUG,DB
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:mysql://localhost:3306/test
log4j.appender.DB.user=root
log4j.appender.DB.password=root
log4j.appender.DB.sql=INSERT INTO logs(date, user, message,class) VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%X{User}','%m','%c')
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=INSERT INTO logs (date, user,message,class) VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%X{User}','%m','%c')
log4j.category.ke.co=ERROR
log4j.category.ke.co.appender-ref=DB
Then use it as follows.
package com.zeddarn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
public class MySQLDatabaseConnector {
static ThreadLocal<Connection> connection = new ThreadLocal<Connection>();
private static Logger logger = Logger.getLogger(MySQLDatabaseConnector.class);
public static Connection getDBConnection() {
//check if a mysql connection already exits. This is to avoid reconnecting
if (connection.get() == null) {
try {
//loading the mysql driver. This means you also have to add mysql libary. You can add manually or via maven
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
//do something to deal with the error of missing mysql driver e.g notification to the user.
MDC.put("User", "loggeduser");
logger.error(e.getMessage());
MDC.getContext().clear();
}
try {
connection.set(DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"));
} catch (SQLException e) {
MDC.put("User", "loggeduser");
logger.error(e.getMessage());
MDC.getContext().clear();
}
}
return connection.get();
}
public static void main(String args[]) {
MDC.put("User", "loggeduser");
logger.error("message from exception.getMessage() method");
MDC.getContext().clear();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…