在不解析堆栈的情况下将异常位置放入Logger方法?

Mr_*_*oad 5 .net c#

我想将我的所有错误记录整合到一个方法,当我们处理异常时,可以从我的应用程序中调用.我将在下面描述一些尴尬的约束.

   public void Log(Exception ex)
   {
        string innerMessage = "";
        if (ex.InnerException != null)
        {
            innerMessage = ex.InnerException.Message;
        }

        Console.WriteLine($"Message: {ex.Message} # Location: { ex.StackTrace} # InnerMessasge: {innerMessage}" );
    }
Run Code Online (Sandbox Code Playgroud)

我之前已经解析了堆栈,但代码最终变得难看,并且根据堆栈它可能会搞砸.

我真正想要的是抛出异常的地方,类和方法或类的位置和行.确保整个东西整齐地放在日志中的一行上.

Tit*_*mir 3

您不需要自己解析异常,您可以使用该类StackTrace从异常中获取易于理解的堆栈跟踪:

try
{
    int.Parse("dd");
}
catch (Exception e)
{
    var s = new StackTrace(e); // Gets the stack trace where the exception was thrown not where it was caught.
    var frame = s.GetFrame(0);
    var sourceMethod = frame.GetMethod();
    Console.WriteLine($"Method: {sourceMethod.Name} - Class {sourceMethod.DeclaringType.FullName} : Location: {frame.GetILOffset()}");

}
Run Code Online (Sandbox Code Playgroud)

您可以从框架中获取其他信息,例如文件、行、列(如果可用),您也可以沿着堆栈查找您的类之一而不是框架类(您可以从框架中获取所有框架并StrackTrace找到您需要的一个)。