1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  package org.apache.ibatis.logging.jdbc;
17  
18  import java.lang.reflect.InvocationHandler;
19  import java.lang.reflect.Method;
20  import java.lang.reflect.Proxy;
21  import java.sql.Connection;
22  import java.sql.PreparedStatement;
23  import java.sql.Statement;
24  
25  import org.apache.ibatis.logging.Log;
26  import org.apache.ibatis.reflection.ExceptionUtil;
27  
28  
29  
30  
31  
32  
33  
34  
35  public final class ConnectionLogger extends BaseJdbcLogger implements InvocationHandler {
36  
37    private final Connection connection;
38  
39    private ConnectionLogger(Connection conn, Log statementLog, int queryStack) {
40      super(statementLog, queryStack);
41      this.connection = conn;
42    }
43  
44    @Override
45    public Object invoke(Object proxy, Method method, Object[] params)
46        throws Throwable {
47      try {
48        if (Object.class.equals(method.getDeclaringClass())) {
49          return method.invoke(this, params);
50        }
51        if ("prepareStatement".equals(method.getName()) || "prepareCall".equals(method.getName())) {
52          if (isDebugEnabled()) {
53            debug(" Preparing: " + removeExtraWhitespace((String) params[0]), true);
54          }
55          PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params);
56          stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack);
57          return stmt;
58        } else if ("createStatement".equals(method.getName())) {
59          Statement stmt = (Statement) method.invoke(connection, params);
60          stmt = StatementLogger.newInstance(stmt, statementLog, queryStack);
61          return stmt;
62        } else {
63          return method.invoke(connection, params);
64        }
65      } catch (Throwable t) {
66        throw ExceptionUtil.unwrapThrowable(t);
67      }
68    }
69  
70    
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81    public static Connection newInstance(Connection conn, Log statementLog, int queryStack) {
82      InvocationHandler handler = new ConnectionLogger(conn, statementLog, queryStack);
83      ClassLoader cl = Connection.class.getClassLoader();
84      return (Connection) Proxy.newProxyInstance(cl, new Class[]{Connection.class}, handler);
85    }
86  
87    
88  
89  
90  
91  
92    public Connection getConnection() {
93      return connection;
94    }
95  
96  }