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">

Log4j Database Configuration (log4j.properties)

# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB
# Define the DB appender
# Set Database Driver
# Set database user name and password
# 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

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


Apache Log4J API

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *