Configuring log4j property file to store in mysql Database

前端 未结 1 682
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 15:44

It\'s been a while that I began with log4j; pretty cool logging framework. I\'ve done other type of logging like Console and File Logging. So trying for DB Adapters with mys

相关标签:
1条回答
  • 2020-12-18 16:07

    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();
    }
    

    }

    0 讨论(0)
提交回复
热议问题