Home Tutorial Java Jdbc JDBC Logging Example

 
 

JDBC Logging Example
Posted on: October 15, 2010 at 12:00 AM
Advertisement
In this tutorial you will learn how to make logger in JDBC and store the logging information in the database.

JDBC Logging Example

JDBC Logging

JDBC logging feature initially introduced in JDK 1.4. It is set of classes that allows you to create consistent, expandable logs in your application. With JDBC logging API you can create your  own handaler classes and this classes will give you ability to send your abstract data in a desired location such as a file, console etc. 

At first create table named student in MySql database and inset values into it as.

CREATE TABLE log (
sourceClass varchar(200) default NULL,
sourceMethod varchar(200) default NULL,
threadID varchar(200) default NULL,
timeEntered varchar(200) default NULL,
level varchar(200) default NULL,
logger varchar(200) default NULL,
message varchar(200) default NULL,
sequence varchar(200) default NULL
);

Then Write the Log Handler Class as  follows

LogHandler.java

package roseindia.net;

import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

public class LogHandler extends Handler {
	String driverName;
	String connectioUrl;
	String userName;
	String userPass;
	Connection connection;
	protected final static String insertSQL = "insert into log (level,logger,message,sequence,"
			+ "sourceClass,sourceMethod,threadID,timeEntered)"
			+ "values(?,?,?,?,?,?,?,?)";
	protected final static String clearSQL = "delete from log;";
	protected PreparedStatement ptmtInsert;
	protected PreparedStatement ptmtClear;

	public LogHandler(String driverName, String connectioUrl, String userName,
			String userPass) {
		try {
			this.driverName = driverName;
			this.connectioUrl = connectioUrl;
			this.userName = userName;
			this.userPass = userPass;
			Class.forName(driverName);
			connection = DriverManager.getConnection(connectioUrl, userName,
					userPass);
			ptmtInsert = connection.prepareStatement(insertSQL);
			ptmtClear = connection.prepareStatement(clearSQL);
		} catch (ClassNotFoundException e) {
			System.err.println("Error on open: " + e);
		} catch (SQLException e) {
			System.err.println("Error on open: " + e);
		}
	}

	@Override
	public void close() throws SecurityException {
		// TODO Auto-generated method stub
		try {
			if (connection != null)
				connection.close();
		} catch (SQLException e) {
			System.err.println(e.toString());
		}
	}

	@Override
	public void flush() {
		// TODO Auto-generated method stub

	}

	static public String trunc(String str, int length) {
		if (str.length() < length)
			return str;
		return (str.substring(0, length));
	}

	@Override
	public void publish(LogRecord record) {
		// TODO Auto-generated method stub
		try {
			// adding entry to log
			ptmtInsert.setInt(1, record.getLevel().intValue());
			ptmtInsert.setString(2, trunc(record.getLoggerName(), 63));
			ptmtInsert.setString(3, trunc(record.getMessage(), 255));
			ptmtInsert.setLong(4, record.getSequenceNumber());
			ptmtInsert.setString(5, trunc(record.getSourceClassName(), 63));
			ptmtInsert.setString(6, trunc(record.getSourceMethodName(), 31));
			ptmtInsert.setInt(7, record.getThreadID());
			ptmtInsert.setTimestamp(8,
					new Timestamp(System.currentTimeMillis()));
			ptmtInsert.executeUpdate();
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}

	public void clear() {
		try {
			ptmtClear.executeUpdate();
		} catch (SQLException e) {
			System.err.println("Error on clear: " + e);
		}
	}
}
Then Write Java Main class as.

JDBCLoggingExample.java

package roseindia.net;

import java.util.logging.*;

public class JDBCLoggingExample {
	static public final String driver = "com.mysql.jdbc.Driver";
	static public final String connection = "jdbc:mysql://localhost/student";

	public static void main(String argv[]) {
		// JDBCLogger handler Setting
		LogHandler jdbcHandler = new LogHandler(driver, connection,
				"root", "root");
		jdbcHandler.clear();
		// Logger setting
		Logger logger = Logger.getLogger("org.roseindia.net");
		logger.addHandler(jdbcHandler);
		logger.setLevel(Level.ALL);
		logger.info("Sample log entry");
		logger.warning("Sample warning");

	}
}
When you run this application it will display message as shown below:

Oct 14, 2010 5:07:00 PM roseindia.net.JDBCLoggingExample main
INFO: Sample log entry
Oct 14, 2010 5:07:00 PM roseindia.net.JDBCLoggingExample main
WARNING: Sample warning

Download this example code

Another Example for JDBC File Logging

LoggingJDBCExample.java

package roseindia.net;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class LoggingJDBCExample {

	// Connection Method
	private static Connection CreateConnection() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/student";

		DriverManager
				.setLogWriter(new PrintWriter("C:/work/vinay/Logfile.log"));

		return DriverManager.getConnection(url, "root", "root");
	}

	public static void main(String[] args) throws Exception {
		Connection conn = CreateConnection();
		conn.setAutoCommit(false);
		Statement st = conn.createStatement();
		try {
			st
					.executeUpdate("create table StudentLog (RollNo int,Name varchar(30));");
			st
					.executeUpdate("insert into StudentLog (RollNo,Name ) values (1,'Rahul')");
			st
					.executeUpdate("insert into StudentLog (RollNo,Name ) values (2,'Ramesh')");
			// committing Transactions
			conn.commit();
			st = conn.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM StudentLog");
			System.out.println("*****************************");

			while (rs.next()) {
				System.out.print("Roll No- " + rs.getInt("RollNo") + ", Name- "
						+ rs.getString("Name"));
			}
			System.out.println();

		} catch (Exception e) {
			// canceling transactions
			conn.rollback();
			System.out.println(e.toString());
		} finally {
			st.close();
			conn.close();
		}
	}
}

When you run this application it will display message as shown below:


*****************************
Roll No- 1, Name- RahulRoll No- 2, Name- Ramesh

Download this example code

Advertisement

Related Tags for JDBC Logging Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 15, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com