log4j Tutorial - Log4j Log to Database








We can use the log4j API to log information into database by using the org.apache.log4j.jdbc.JDBCAppender object.

The following table lists the configuration properties for JDBCAppender.

Property Description
bufferSize Sets the buffer size. Default size is 1.
driver JDBC driver class. Default to sun.jdbc.odbc.JdbcOdbcDriver.
layout Sets the layout. Default is org.apache.log4j.PatternLayout.
password Sets the database password.
sql Specifies SQL statement to use for each logging request.
URL Sets the JDBC URL
user Sets the database user name




Example

First, create a table to store the log information.

CREATE TABLE LOGS
   (USER_ID VARCHAR(20) NOT NULL,
    DATED   DATE NOT NULL,
    LOGGER  VARCHAR(50) NOT NULL,
    LEVEL   VARCHAR(10) NOT NULL,
    MESSAGE VARCHAR(1000) NOT NULL
   );

Then, create the configuration file log4j.properties for JDBCAppender which controls how to connect to database and how to store log message to the LOGS table.

# 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/Your_Database_Name

# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver

# Set database user name and password
log4j.appender.DB.user=your_user_name
log4j.appender.DB.password=your_password

# Set the SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOGS 
                      VALUES('%x','%d','%C','%p','%m')

# Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout

The following code shows how to log information into a database.

import org.apache.log4j.Logger;
import java.sql.*;
import java.io.*;
import java.util.*;

public class Main{
  static Logger log = Logger.getLogger(Main.class.getName());

  public static void main(String[] args)
                throws IOException,SQLException{

     log.debug("Debug");
     log.info("Info");
  }
}