实体框架日志记录不处理异常

时间:2018-03-01 16:00:02

标签: c# asp.net-mvc entity-framework logging

我已根据here的指南实施了实体框架日志记录。但是,只有在没有异常时才会记录!我通过分配超过允许的字符来创建system.FormatException: Input string was not in a correct format.。我的代码是:

Databasecontext context=new DatabaseContext();
TableCity tbCity;
var logger = new MyLogger();           
context.Database.Log = l => logger.Log("Table-tableNews", l);
tbCity.City ="sdkjfaksdjfsdjfjasdfjsdjfjdfjdjfjasdfjlasdjfljdfjdadsfdf";//varchar(25) in dbase
.......... //code removed for clarity
context.TableName.Add(tbCity);
try{
   context.SaveChanges();
 }
 catch(Exception ex)
 {}

我的日志方法

 public void Log(string component, string messages)
 {
    //contents here, which works as desired
 }

我是否需要以不同方式实施日志异常?

1 个答案:

答案 0 :(得分:2)

如果您在提到的链接上有scrolled down,则会遇到IDbCommandInterceptor界面。它功能更丰富,它可以判断查询是成功执行还是失败。

示例实现可以是:

public class LogDbCommandInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        interceptionContext.SetUserState("start", DateTime.Now);
    }

    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        Console.WriteLine($"sql command: {command.CommandText}, hasFailed: {HasFailed(interceptionContext)}, duration: {CalculateDuration(interceptionContext)}");
        Console.WriteLine($"parameters: {FormatParams(command.Parameters)}, exception: {interceptionContext.Exception?.Message}");
    }

    public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        interceptionContext.SetUserState("start", DateTime.Now);
    }

    public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        Console.WriteLine($"sql command: {command.CommandText}, hasFailed: {HasFailed(interceptionContext)}, duration: {CalculateDuration(interceptionContext)}");
    }

    public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        interceptionContext.SetUserState("start", DateTime.Now);
    }

    public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        Console.WriteLine($"sql command: {command.CommandText}, hasFailed: {HasFailed(interceptionContext)}, duration: {CalculateDuration(interceptionContext)}");
    }

    private static double CalculateDuration<T>(DbCommandInterceptionContext<T> context)
    {
        return (DateTime.Now - (DateTime)context.FindUserState("start")).TotalMilliseconds;
    }

    private static bool HasFailed<T>(DbCommandInterceptionContext<T> context)
    {
        return context.OriginalException != null || (context.IsAsync && context.TaskStatus != TaskStatus.RanToCompletion);
    }

    private static string FormatParams(ICollection dbParameterCollection)
    {
        if (dbParameterCollection.Count == 0)
            return string.Empty;

        var parameterDescriptor = new StringBuilder();

        foreach (SqlParameter parameter in dbParameterCollection)
        {
            parameterDescriptor.AppendFormat("{0} {1}: {2}, ", parameter.DbType, parameter.ParameterName, parameter.Value);
        }

        return parameterDescriptor.ToString().TrimEnd(' ', ',');
    }
}

其中Console.WriteLine当然可以替换为您自己的记录器。

如您所见,您可以使用OriginalException属性读取异常。其他感兴趣的属性被监听here.

还可以找到注册实施的简短指南here

  

注册拦截器   一旦创建了一个实现一个或多个拦截接口的类,就可以使用DbInterception类向EF注册它

     

也可以使用DbConfiguration基于代码的配置在app-domain级别注册拦截器

     

您还可以使用app.config文件配置拦截器