我有记录Exception.Message的代码。但是,我读过一篇文章,它指出使用Exception.ToString()更好。对于后者,您可以保留关于错误的更重要的信息。

这是真的吗?继续替换所有代码记录Exception.Message是否安全?

我还为log4net使用了基于XML的布局。Exception.ToString()是否可能包含无效的XML字符,这可能导致问题?


当前回答

这取决于你需要的信息。对于调试堆栈跟踪和内部异常是有用的:

    string message =
        "Exception type " + ex.GetType() + Environment.NewLine +
        "Exception message: " + ex.Message + Environment.NewLine +
        "Stack trace: " + ex.StackTrace + Environment.NewLine;
    if (ex.InnerException != null)
    {
        message += "---BEGIN InnerException--- " + Environment.NewLine +
                   "Exception type " + ex.InnerException.GetType() + Environment.NewLine +
                   "Exception message: " + ex.InnerException.Message + Environment.NewLine +
                   "Stack trace: " + ex.InnerException.StackTrace + Environment.NewLine +
                   "---END Inner Exception";
    }

其他回答

理想情况下,最好序列化整个异常对象而不是. tostring()。这将封装整个异常对象(所有内部异常、消息、堆栈跟踪、数据、键等)。

这样您就可以确保没有遗漏任何内容。另外,您还拥有可以在任何应用程序中使用的通用格式的对象。

    public static void LogError(Exception exception, int userId)
    {
        LogToDB(Newtonsoft.Json.JsonConvert.SerializeObject(exception), userId);
    }

这取决于你需要的信息。对于调试堆栈跟踪和内部异常是有用的:

    string message =
        "Exception type " + ex.GetType() + Environment.NewLine +
        "Exception message: " + ex.Message + Environment.NewLine +
        "Stack trace: " + ex.StackTrace + Environment.NewLine;
    if (ex.InnerException != null)
    {
        message += "---BEGIN InnerException--- " + Environment.NewLine +
                   "Exception type " + ex.InnerException.GetType() + Environment.NewLine +
                   "Exception message: " + ex.InnerException.Message + Environment.NewLine +
                   "Stack trace: " + ex.InnerException.StackTrace + Environment.NewLine +
                   "---END Inner Exception";
    }

除了上面所说的,不要在异常对象上使用ToString()来显示给用户。只要Message属性就足够了,或者一个更高级别的自定义消息。

就日志目的而言,一定要在Exception上使用ToString(),而不仅仅是Message属性,因为在大多数情况下,您会摸不着头脑这个异常具体发生在哪里,调用堆栈是什么。堆栈轨迹会告诉你所有这些。

我得说这取决于你想从日志中看到什么,不是吗?如果你对ex.Message提供的功能感到满意,就使用它。否则,使用ex.toString()或甚至记录堆栈跟踪。

我想说@Wim是对的。您应该对日志文件使用ToString()—假设是技术观众—如果有Message,则显示给用户。有人可能会说,即使这样也不适合用户,因为存在各种异常类型和出现的情况(比如ArgumentExceptions等)。

此外,除了StackTrace之外,ToString()还将包括其他方法无法获得的信息。例如,融合的输出,如果启用了在异常“消息”中包含日志消息。

一些异常类型甚至在ToString()中包含额外的信息(例如来自自定义属性),但在Message中不包含。