Log4j Database Appender Example MySQL

Log4j Database Appender Example MySQL

In this example, We will show you How to configure Log4j Database Appender example MySQL.
The example was tested with MySQL environment and output has been shared in the same post.

Creating Database and Table

Query for creating database -> CREATE DATABASE logger;

Query for creating table -> CREATE TABLE LOGS (log_id INT AUTO_INCREMENT NOT NULL, level VARCHAR(10) NOT NULL, message longtext NOT NULL, PRIMARY KEY(log_id));

Table Structure -> DESC logs;

Log4j Database Appender Example MySQL

Creating Logger Instance (ApplicationLogger.java)

package com.dineshkrish;

import org.apache.log4j.Logger;

public class ApplicationLogger {
	
	static Logger logger = Logger.getLogger(Logger.class);

	public static Logger getLogger() {
		
		return logger;
	}
}

Adding Maven Dependencies (pom.xml)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.dineshkrish</groupId>
	<artifactId>Log4jApp</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<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.6</version>
		</dependency>
		
	</dependencies>

</project>

Log4j Database Configuration (log4j.properties)

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

# 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=root

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

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

Accessing the Logger (Example.java)

package com.dineshkrish;

public class Example {

	public static void main(String[] args) {

		ApplicationLogger.getLogger().info("Message 1");
		ApplicationLogger.getLogger().warn("Message 2");
		ApplicationLogger.getLogger().debug("Message 3");
		ApplicationLogger.getLogger().error("Message 4");
		ApplicationLogger.getLogger().fatal("Message 5");

	}
}

Output (Querying the table)

Log4j Database Appender Example MySQL

References

Apache Log4J API