Configuring log4j property file to store in mysql Database

12,517

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

}

Share:
12,517
Neo182
Author by

Neo182

I'm simply a computer enthusiastic...I think computer; dream computer and love computer...!

Updated on June 04, 2022

Comments

  • Neo182
    Neo182 almost 2 years

    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 mysql for Database logging. Accordingly, I've created following property file named log4j.properties as -

    # Define the root logger with appender file
    log4j.rootLogger = DEBUG, DB
    
    # Define the DB appender
    log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
    
    # Set JDBC URL
    log4j.appender.DB.URL=jdbc:mysql://localhost:3306/test
    
    # Set Database Driver
    log4j.appender.DB.driver=com.mysql.jdbc.Driver
    
    # Set database user name and password
    log4j.appender.DB.user=root
    log4j.appender.DB.password=
    
    # Set the SQL statement to be executed.
    log4j.appender.DB.sql=insert into log(date,level,message) values("%d","%p","%m")
    
    # Define the layout for file appender
    log4j.appender.DB.layout=org.apache.log4j.PatternLayout
    

    And used it in a test class in following way -

     public class DBLoggerTest {
        static Logger logger;
    
        public DBLoggerTest() {
            //System.setProperty("log4j.configuration", "log4j.properties");
            logger = Logger.getLogger(DBLoggerTest.class.getName());
    
        }
    
        public static void main(String[] args) {
            new DBLoggerTest();
            logger.info("This is a test info");
            logger.error("This is an error messsage");
        }
    }
    

    But I got following error -

    log4j:WARN No appenders could be found for logger (com.satyam.logger.test.DBLoggerTest).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    

    Any help please...?