EF 쿼리 로깅

/// <summary>
///
/// </summary>
/// <seealso cref="System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor" />
/// <remarks>
/// https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.interception.idbcommandinterceptor(v=vs.113).aspx
/// 스태틱하니까 한번만 설정해주면 됨.
/// DbInterception.Add(new EntityFrameworkCommandInterceptor());
/// </remarks>
public class EntityFrameworkCommandInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuting(
        DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        ; //LogIfNonAsync(command, interceptionContext);
    }

    public void NonQueryExecuted(
        DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        LogIfError(command, interceptionContext);
    }

    public void ReaderExecuting(
        DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        ; //LogIfNonAsync(command, interceptionContext);
    }

    public void ReaderExecuted(
        DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        LogIfError(command, interceptionContext);
    }

    public void ScalarExecuting(
        DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        ; //LogIfNonAsync(command, interceptionContext);
    }

    public void ScalarExecuted(
        DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        LogIfError(command, interceptionContext);
    }

    private void LogIfNonAsync<TResult>(
        DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
    {
        ; //if (!interceptionContext.IsAsync) Logger.Warn("Non-async command used: {0}", command.CommandText);
    }

    private void LogIfError<TResult>(
        DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
    {
        if (interceptionContext.Exception != null)
        {
            NLogger.Instance.WriteErrorLog(new Exception("Query:" + command.CommandText, interceptionContext.Exception));
        }
    }
}

댓글

이 블로그의 인기 게시물

Oracle NLS_DATE_FORMAT 변경

Stop console process using Ctrl+C.

Alternative to IValueConvert, QuickConverter