Log4j Logging in MySQL Database - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Log4j Logging in MySQL Database

Share This


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

Table creation in MYSQL for Logging


create table LOGS
(
    USER_ID varchar(20)    not null,
    DATED   date           not null,
    LOGGER  varchar(50)    not null,
    LEVEL   varchar(10)    not null,
    MESSAGE varchar(1000)  not null
);

Configuration File (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/DBNAME # Set Database Driver log4j.appender.DB.driver=com.mysql.jdbc.Driver # Set database user name and password log4j.appender.DB.user=user_name log4j.appender.DB.password=password # Set the SQL statement to be executed. log4j.appender.DB.sql=INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m') # Define the layout for file appender log4j.appender.DB.layout=org.apache.log4j.PatternLayout

Java Code


import org.apache.log4j.Logger; import java.sql.*; import java.io.*; import java.util.*; public class SampleLog4j{ static Logger log = Logger.getLogger(SampleLog4j.class.getName()); public static void main(String[] args)throws IOException,SQLException{ log.debug("Debug Msg!"); log.info("Info Msg!"); } }


Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.