NLog - 同时抛出异常和日志消息

时间:2017-07-14 08:56:38

标签: c# .net exception-handling nlog

我有以下方法,其中包括开头的验证检查。我使用NLog并且我想记录异常消息并同时抛出异常',避免尽可能多的代码膨胀。

目前,我做了以下工作,但看起来有点笨重。还有更好的方法吗?

public static void ValidateValue(string value)
{
    if (!string.IsNullOrWhiteSpace(value) && value.Contains(","))
    {
        ArgumentException ex = new ArgumentException(string.Format("value cannot contain ',': {0}", value));
        Logger.Error(ex);
        throw ex;
    }
}

我正在寻找的内容更符合

public static void ValidateValue(string value)
{
    if (!string.IsNullOrWhiteSpace(value) && value.Contains(","))
        throw Logger.Error<ArgumentException>("value cannot contain ',': {0}", value);
}

Logger.Error<>方法在记录消息后返回ArgumentException

这似乎是有用的,可能已经存在,但也许我必须推出自己的扩展方法?

谢谢!

1 个答案:

答案 0 :(得分:2)

不推荐在同一个地方记录和抛出异常,因为:

  • 您可以为同一错误(多个级别)获取多个日志
  • 您可能忘记记录例外

我会推荐以下内容:

  • 在高级别捕获异常并将其记录在那里(通用)
  • 仅记录您赢得的(重新)抛出的例外情况
  • 在不记录它们时添加上下文信息,我使用以下帮助程序:

    public static TException SetContextData<TException>(this TException exception, object key, object value) 
           where TException : Exception
    {
        exception.Data[key] = value;
        return exception;
    }
    

    用法:

    throw ex.SetContextData("someContext", 123)
            .SetContextData("anotherId", 133);     
    

    使用NLog,您可以按如下方式记录异常数据:

    ${exception:format=toString,Data:maxInnerExceptionLevel=10}
    
相关问题