Quantcast
Channel: Kruders.com » log4j
Viewing all articles
Browse latest Browse all 10

Log4j – Logging in Database

$
0
0

In this article, you will see how to write your logging information into a database.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.15</version>
    </dependency>
  </dependencies>  

1. Sql Script

Use the following Sql Script for creating table.

CREATE TABLE logging(loggingdate  DATE, logger VARCHAR(50), logginglevel  VARCHAR(10),
    message VARCHAR(100));

2. Properties file

The following configuration writes your log information in database

log4j.properties

# Define the root logger with appender file
log4j.rootLogger = INFO, DB

# Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender

# Set JDBC Options
log4j.appender.DB.URL=jdbc:mysql://localhost/test
log4j.appender.DB.driver=com.mysql.jdbc.Driver
log4j.appender.DB.user=root
log4j.appender.DB.password=password

# Set the SQL statement to be executed.
log4j.appender.DB.sql=insert into logging values('%d{yyyy-MM-dd  HH:mm:ss.SSS}','%C','%p','%m')

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

3. Log4j in Java Program

The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.

package com.kruders;

import org.apache.log4j.Logger;

public class HelloWorld {
	static final Logger logger = Logger.getLogger(HelloWorld.class);
	
	public static void main(String[] args) {
		logger.info("Hello World!!!");
	}
}


When you run the above example, you will see the similar logs in database as shown in Figure 2.1

Figure 2.1 Figure 2.1

You can download the source code of this example here.



Viewing all articles
Browse latest Browse all 10

Trending Articles