log4j - Logging in Database



The log4j API provides the org.apache.logging.log4j.jdbc.JDBCAppender object, which can put logging information in a specified database.

log4j2.properties

appender.0.type = JDBC
appender.0.name = JDBC
appender.0.tableName = logs

log4j2.xml

<appenders>
   <Jdbc name="databaseAppender" tableName="logs">
      <DriverManager url="jdbc:mysql://localhost:3306/tutorials" username="guest" password="guest123" />
      <Column name="level" pattern="%level" />
      <Column name="logger" pattern="%logger" />
      <Column name="message" pattern="%message" />
   </Jdbc>
</appenders>

JDBCAppender Configuration

JDBCAppender has the following configurable parameters:

Property Type Default Value Description
name String   The name of the appender.
bufferSize int 8192 The size of the ByteBuffer internally used by the appender.
direct boolean false If set to true, log events will be written directly to either FileDescriptor.out or FileDescriptor.err. This setting bypasses the buffering of System.out and System.err and might provide a performance comparable to a file appender. This setting is incompatible with the follow attribute.
follow boolean false If set to true, the appender will honor reassignments of System.out (resp. System.err) via System.setOut (resp. System.setErr). Otherwise, the value of System.out (resp. System.err) at configuration time will be used. This setting is incompatible with the direct attribute.
ignoreExceptions boolean true If false, logging exception will be forwarded to the caller of the logging statement. Otherwise, they will be ignored.
immediateFlush boolean true If set to true, the appender will flush its internal buffer after each event.
target Target SYSTEM_OUT It specifies which standard output stream to use: SYSTEM_OUT - It uses the standard output. SYSTEM_ERR - It uses the standard error output.
filter String   Allows filtering log events just before they are formatted and sent.
layout Layout   Formats log events.

Log Table Configuration

Before you start using JDBC based logging, you should create a table to maintain all the log information. Following is the SQL Statement for creating the LOGS table −

CREATE TABLE LOGS
   (
    TIMESTAMP TIMESTAMP(6) NOT NULL,
    LOGGER  VARCHAR(50)    NOT NULL,
    LEVEL   VARCHAR(10)    NOT NULL,
    MESSAGE VARCHAR(1000)  NOT NULL
   );

Sample Configuration File

Following is a sample configuration file log4j.properties for JDBCAppender which will is be used to log messages to a LOGS table.

appender.0.type = JDBC
appender.0.name = JDBC
appender.0.tableName = logs

appender.0.bufferSize = 10

appender.0.connectionSource.type= DriverManager
appender.0.connectionSource.connectionString = jdbc:mysql://localhost:3306/tutorials
appender.0.connectionSource.username = guest
appender.0.connectionSource.password = guest123
appender.0.connectionSource.driverClassName = com.mysql.cj.jdbc.Driver

appender.0.col[0].type = ColumnMapping
appender.0.col[0].name = timestamp
appender.0.col[0].columnType = java.util.Date

appender.0.col[1].type = ColumnMapping
appender.0.col[1].name = level
appender.0.col[1].pattern = %level

appender.0.col[2].type = ColumnMapping
appender.0.col[2].name = logger
appender.0.col[2].pattern = %logger

appender.0.col[3].type = ColumnMapping
appender.0.col[3].name = message
appender.0.col[3].pattern = %message

# Define the root logger with appender file
rootLogger.level = DEBUG
rootLogger.appenderRef.0.ref = JDBC

For MySQL database, you would have to use the actual DBNAME, user ID and password, where you have created LOGS table. The SQL statement is to execute an INSERT statement with the table name LOGS and the values to be entered into the table.

JDBCAppender does not need a layout to be defined explicitly. Instead, the SQL statement passed to it uses a PatternLayout.

If you wish to have an XML configuration file equivalent to the above log4j.properties file, then here is the content −

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error">
  <appenders>
    <Jdbc name="databaseAppender" tableName="logs">
      <DriverManager url="jdbc:mysql://localhost:3306/tutorials" username="guest" password="guest123" />
      <Column name="level" pattern="%level" />
      <Column name="logger" pattern="%logger" />
      <Column name="message" pattern="%message" />
    </Jdbc>
  </appenders>
  <loggers>
    <root level="warn">
      <appender-ref ref="databaseAppender"/>
    </root>
  </loggers>
</configuration>

Sample Program

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

package com.tutorialspoint;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4jDemo{

   /* Get actual class name to be printed on */
   private static final Logger LOGGER = LogManager.getLogger();

   public static void main(String[] args) {
      LOGGER.debug("Hello this is an debug message");
      LOGGER.info("Hello this is an info message");
   }
}

Compile and Execute

Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.

All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the given steps −

  • Create log4j2.properties as shown above.

  • Create log4jDemo.java as shown above and compile it.

  • Execute log4jDemo binary to run the program.

Now check your LOGS table inside tutorials database and you would find the following entries −

mysql >  select * from LOGS;
+----------------------------+------------------------------+-------+----------------------------------+
| TIMESTAMP                  | LOGGER                       | LEVEL | MESSAGE                          |
+----------------------------+------------------------------+-------+----------------------------------+
| 2025-09-07 13:53:25.617000 | com.tutorialspoint.log4jDemo | DEBUG | Hello this is an debug message   |
| 2025-09-07 13:53:25.620000 | com.tutorialspoint.log4jDemo | INFO  | Hello this is an info message    |
+----------------------------+------------------------------+-------+----------------------------------+
2 rows in set (0.00 sec)
Advertisements