18 October 2017

Sending Log4j Logger Messages to Database[SQL SERVER]

Usually we use log4j to append the logger messages to log files in server but we can send the logger messages to Database by the following process

Here I developed an application to send logger messages to Database.




SaveLLogsToDB.java
====================

package com.omu;
package  com.omu;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.sql.*;
import java.io.*;
import java.util.*;

    public class SaveLLogsToDB {
       /* Get actual class name to be printed on */
       static Logger log = Logger.getLogger(SaveLLogsToDB.class.getName());
      
       public static void main(String[] args){
           String log4jConfPath = "src/resources/log4j.properties";
           PropertyConfigurator.configure(log4jConfPath);
          log.debug("Debug");
          log.info("Info");
          log.debug("amicorp");
          System.out.println("finish");
          System.out.println("Logs are saved to Database. Please open your Database and check the results");
          System.out.println("The logs are saved according to your system timings");
       }
    }















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
#Database name i mentioned here as test1
log4j.appender.DB.URL=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#
## Set Database Driver
log4j.appender.DB.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#
## Set database user name and password
log4j.appender.DB.user=sa
log4j.appender.DB.password=Admin@123
#
## Set the SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOGGER VALUES('%x','%d','%C','%p','%m')
#
## Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
#
#

Attach the log4j and sqljdbc.jar files in build path.





Run SaveLLogsToDB.java you can see the logger messages by opening the DataBase.

No comments:

Post a Comment

JAVA SetUp in System

JAVA ENVIRONMENT SET UP  =========================== In System Variables JAVA_HOME : C:\Program Files\Java\jdk1.8.0_144 JDK_HOME  : %J...