Reading:  

What is Log4J. An absolute beginners tutorial.


Saving logging information in Database

org.apache.log4j.jdbc.JDBC Appender object of Log4j API also logging of information into the database.

JDBC Appender Configuration:

Property

Description

bufferSize

Sets buffer size

driver

Sets driver class to specified string.

layout

Sets layout used. org.apache.log4j.PatternLayout is Default layout i.

password

Sets database password.

sql

Specifies SQL statement executed every time logging event occur. This could be DELETE, UPDATE and INSERT

URL

Sets JDBC URL

Log Table Configuration:

CREATE TABLE LOG_INFO
   (
    USER_ID VARCHAR(30) NULL,
    DATED   DATE,
    LOGGER  VARCHAR(60) NULL,
    LEVELS   VARCHAR(10) NULL,
    MESSAGES VARCHAR(1000) NULL
   );

Above table is used to store the log information. Sample Configuration File: XML JDBCAppender configuration for the log4j:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error">
	<Appenders>
		<JDBC name="databaseAppender" tableName="LOG_INFO">
			<ConnectionFactory class="net.example.db.ConnectionFactory" method="getDatabaseConnection" />
			<Column name="USER_ID" pattern="%userid" />
			<Column name="DATE" isEventTimestamp="true" />
			<Column name="LEVEL" pattern="%level" />
			<Column name="LOGGER" pattern="%logger" />
			<Column name="MESSAGE" pattern="%message" />
		</JDBC>
	</Appenders>
	<Loggers>
		<Root level="warn">
			<AppenderRef ref="databaseAppender" />
		</Root>
	</Loggers>
</Configuration>

 

package net.example.db;

import 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", "jlogexamples");
        properties.setProperty("password", "mypassword"); // or get properties from some configuration file

        GenericObjectPool pool = new GenericObjectPool();
        DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                "jdbc:mysql://example.org:3306/exampleDb", 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();
    }
}

Sample Program: The following Java class initializes, uses, Log4J logging library in Java applications.

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.sql.*;
import java.io.*;
import java.util.*;
 
public class Log4jDBExample
{
    static final Logger logger_c = LogManager.getLogger(Log4jDBExample.class.getName());
    public static void main(String[] args)
    {
        logger_c.debug("Message Debug!!");
        logger_c.info( " Message Info!!");

    }  
}

 

 

Set PATH and CLASSPATH appropriately compile and execute it. Verify the LOGS_INFO table in database, there would be following entries.

mysql >  select * from LOGS_INFO;
+---------+------------+--------------+-------+---------+
| USER_ID | DATED      | LOGGER       | LEVEL      | MESSAGE |
+---------+------------+--------------+-------+---------+
|         | 2015-03-01 | log4jDBExample | DEBUG | Message Debug !!  |
|         | 2015-03-01 | log4jDBExample | INFO     | Message Info !!    |
+---------+------------+--------------+-------+---------+

2 rows in set (0.01 sec)

 

Purpose of this tutorial was to get you started with Log4J, You can keep learning from Apache's official Log4J website 

http://logging.apache.org/log4j/2.x/

Also you can ask question on StackOverflow if you are facing any issues.

Thanks for reading through. We always try to provide accurate information, but there could always be some errors, if you found any, leave your comments so we can fix them soon. We would like to improve with every topic we cover on Coach.

 

Description

This tutorial is aimed at learners who want to get an understaind on what Log4J is and what it is used for. This tutorial have 10 part to it as shown below

  1. Overview    
  2. How to Install Log4J
  3. Understanding Architecture
  4. Getting started with Log4J Configuration
  5. Sample Program
  6. Logging Methods
  7. Understanding different Logging Levels
  8. Log4J log formatting
  9. How to log in files
  10. How to log in database using Log4J

We hope that this tutorial will help you out with Log4J. Please note that this tutorial is for absolute starters and does not go into much depth. Let us know how we can improve by sending  your feedback.



Prerequisites

A good understanding of Java programming language is required.

Audience

Absolute beginners

Author: Subject Coach
Added on: 7th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!