Last active
August 29, 2015 14:17
-
-
Save Buthrakaur/b1124c08f8521f39f8fd to your computer and use it in GitHub Desktop.
Oracle ODP.NET SQL Logging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class OracleConnectionProvider | |
{ | |
private readonly ProxyGenerator proxyGenerator = new ProxyGenerator(); | |
private readonly IInterceptor interceptor = new SqlLoggingInterceptor(SqlLogger); | |
public IDbConnection CreateConnection() | |
{ | |
var con = new OracleConnection(connectionString); | |
con.Open(); | |
if (!EnableLogging) return con; | |
return proxyGenerator.CreateInterfaceProxyWithTarget<IDbConnection>(con, interceptor); | |
} | |
} | |
public class SqlLoggingInterceptor : IInterceptor | |
{ | |
private readonly ISqlLogger sqlLogger; | |
private readonly ProxyGenerator proxyGenerator = new ProxyGenerator(); | |
public SqlLoggingInterceptor(ISqlLogger sqlLogger) | |
{ | |
this.sqlLogger = sqlLogger; | |
} | |
private static readonly MethodInfo[] executeMethods = | |
typeof (IDbCommand).GetMethods(BindingFlags.Instance | BindingFlags.Public) | |
.Where(m => new[] {"ExecuteScalar", "ExecuteNonQuery", "ExecuteReader"}.Contains(m.Name)) | |
.ToArray(); | |
public void Intercept(IInvocation invocation) | |
{ | |
if (invocation.Method == createCommandMethod) | |
{ | |
invocation.Proceed(); | |
var command = (IDbCommand)invocation.ReturnValue; | |
var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(command, this); | |
invocation.ReturnValue = proxy; | |
return; | |
} | |
if (executeMethods.Contains(invocation.Method)) | |
{ | |
var cmd = (IDbCommand)invocation.InvocationTarget; | |
var sw = new Stopwatch(); | |
sw.Start(); | |
try | |
{ | |
invocation.Proceed(); | |
} | |
catch (Exception exc) | |
{ | |
sqlLogger.Log(exc, cmd.CommandText, cmd.Parameters, sw.Elapsed); | |
throw; | |
} | |
sqlLogger.Log(cmd.CommandText, cmd.Parameters, sw.Elapsed); | |
return; | |
} | |
invocation.Proceed(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment