如何启动JDBC Debug模式,打印JDBC诊断日志
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); String loader = Thread.currentThread().getContextClassLoader().toString().replaceAll("[,=:\"]+", ""); ObjectName pattern = new ObjectName("com.oracle.jdbc:type=diagnosability,name=" + loader); ObjectName diag = ((ObjectName[]) (mbs.queryNames(pattern, null).toArray(new ObjectName[0])))[0]; mbs.setAttribute(diag, new Attribute("LoggingEnabled", true)); System.out.println("LoggingEnabled = " + mbs.getAttribute(diag, "LoggingEnabled"));
/**oracle 10g 启动方法*/ oracle.jdbc.driver.OracleLog.setTrace(true); // enable logging oracle.jdbc.driver.OracleLog.setTrace(false); // disable logging
/**配置log文件*/ Handler fh = new FileHandler("./oracle_jdbc_log.log"); fh.setLevel(Level.ALL); fh.setFormatter(new SimpleFormatter()); Logger.getLogger("").addHandler(fh); Logger.getLogger("").setLevel(Level.ALL);4.下面给大家一个完成的Demo
import javax.management.Attribute; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.ReflectionException;
public void run() throws SQLException { DriverManager.registerDriver(new OracleDriver()); //需在加载OracleDriver之后开启log enableOracleLogging(); Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = getConnection(); System.out.println("Connection retrieved.."); stmt = conn.createStatement(); rset = stmt.executeQuery("select empno from emp"); while (rset.next()) { System.out.println(rset.getInt(1)); } } catch (SQLException sqle) { sqle.printStackTrace(); } finally { if (rset != null) { rset.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } } public static void enableOracleLogging() { try { /** 配置log文件 */ Handler fh = new FileHandler("./oracle_jdbc_log.log"); fh.setLevel(Level.ALL); fh.setFormatter(new SimpleFormatter()); Logger.getLogger("").addHandler(fh); Logger.getLogger("").setLevel(Level.ALL); /** oracle 11g 启动方法 */ MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); String loader = Thread.currentThread().getContextClassLoader().toString().replaceAll("[,=:\"]+", ""); ObjectName pattern = new ObjectName("com.oracle.jdbc:type=diagnosability,name=" + loader); ObjectName diag = ((ObjectName[]) (mbs.queryNames(pattern, null).toArray(new ObjectName[0])))[0]; mbs.setAttribute(diag, new Attribute("LoggingEnabled", true)); System.out.println("LoggingEnabled = " + mbs.getAttribute(diag, "LoggingEnabled")); /** oracle 10g 启动方法 */ // oracle.jdbc.driver.OracleLog.setTrace(true); // enable logging // oracle.jdbc.driver.OracleLog.setTrace(false); // disable logging } catch (Exception e) { e.printStackTrace(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。