论坛首页 Java企业应用论坛

log4jdbc 使用入门

浏览 2515 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-10-21  

log4jdbc 可以将占位符与参数全部合并在一起显示,方便直接拷贝 sql PLSQL Developer 等客户端直接执行,加快调试速度. 记录执行的sql及其耗时等.

 

 

1.测试代码

 

package com.mtea.demo.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Demo {
	private static Logger logger = LoggerFactory.getLogger(Demo.class);

	public static void main(String args[]) {
		test_without_log4jdbc_effect();
		test_with_log4jdbc_effect();
	}
	
	/**
	 * no log4jdbc
	 */
	public static void test_without_log4jdbc_effect(){
		//mysql-connector-java-5.1.10-bin.jar提供的类
		String driverNameOfMysql = "com.mysql.jdbc.Driver";
		
		String connStringOfMysql = "jdbc:mysql://localhost:3306/db_hibernate";
		
		Connection conn = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		try {
			Class.forName(driverNameOfMysql);
			conn = DriverManager.getConnection(connStringOfMysql, "root", "root");
			pstmt = conn.prepareStatement("select name from tb_product where id=?"); 
			pstmt.setInt(1, 1);
			rs=pstmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}
			rs.close();
		} catch (Exception e) {
			logger.error("test_without_log4jdbc_effect 出错", e);
		} finally {
			logger.info("test_without_log4jdbc_effect finished");
		}
	}
	/**
	 * with log4jdbc_effect
	 */
	public static void test_with_log4jdbc_effect(){
		//log4jdbc4-1.2beta2.jar提供的类
		String driverName = "net.sf.log4jdbc.DriverSpy";
		
		String connString = "jdbc:log4jdbc:mysql://localhost:3306/db_hibernate";
		
		Connection conn = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		try {
			Class.forName(driverName);
			conn = DriverManager.getConnection(connString, "root", "root");
			pstmt = conn.prepareStatement("select name from tb_product where id=?"); 
			pstmt.setInt(1, 1);
			rs=pstmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}
			rs.close();
		} catch (Exception e) {
			logger.error("test_with_log4jdbc_effect 出错", e);
		} finally {
			logger.info("test_with_log4jdbc_effect finished");
		}
	}
}

 2.运行结果:


3.项目配置:

 


4.过滤日志:

    <logger name="jdbc.connection" level="ERROR"/>
    <logger name="jdbc.audit" level="ERROR"/>
    <logger name="jdbc.sqlonly" level="ERROR"/>
    <logger name="jdbc.resultset" level="ERROR"/>
    <logger name="log4jdbc.debug" level="ERROR"/>

 

5. over

 

 

  • 大小: 68.3 KB
  • 大小: 27.7 KB
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics