NLog - 同时抛出异常和记录日志信息

3
我有一个包含验证检查的方法,我正在使用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。这似乎是有用的东西,可能已经存在,但也许我必须编写自己的扩展方法?谢谢!

如果您想使用泛型,那么您需要使用反射来创建异常对象,但最简单的方法可能是手动传入一个新的异常对象。 - DavidG
1个回答

3

在同一位置记录日志并抛出异常是不推荐的,因为:

  • 您可能会为相同错误(在多个级别上)获得多个日志
  • 您可能会忘记记录异常

我建议采用以下方式:

  • Catch exceptions on high level and log them there (generic)
  • Only log the exceptions where you won't (re)throw them
  • Add context info when not-logging them, I use the following helper:

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

    Usage:

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

    With NLog you could log the exception data as follows:

    ${exception:format=toString,Data:maxInnerExceptionLevel=10}
    

你说得很对。在异常创建的地方记录日志根本没有提供任何上下文信息。最好在应用程序将要处理(或忽略)错误的地方记录日志,因为可以添加有关错误在 try {} catch () {} 上下文中实际表示的其他信息。感谢您为我澄清这一点 :0) - 3-14159265358979323846264

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接