logging exception in c#

hap*_*ile 21 c# logging exception

logging exception the code below allows to save the content of an exception in a text file. Here I'm getting only the decription of the error.

but it is not telling me where the exception occured, at which line. Can anyone tell me how can I achive that so I can get even the line number where the exception occured?

#region WriteLogError
/// <summary>
/// Write an error Log in File
/// </summary>
/// <param name="errorMessage"></param>
public void WriteLogError(string errorMessage)
{
  try
  {
    string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
    if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
    {
      File.Create(System.Web.HttpContext.Current.Server.MapPath(path))
     .Close();
    }
    using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
    {
      w.WriteLine("\r\nLog Entry : ");
      w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
      string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() 
                 + ". Error Message:" + errorMessage;
      w.WriteLine(err);
      w.WriteLine("__________________________");
      w.Flush();
      w.Close();
    }
  }
  catch (Exception ex)
  {
    WriteLogError(ex.Message);
  }

}

#endregion
Run Code Online (Sandbox Code Playgroud)

Jus*_*tin 41

我发现在C#中记录异常的最简单方法是调用ToString()方法:

try
{

}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}
Run Code Online (Sandbox Code Playgroud)

这通常会为您提供所需的所有信息,例如错误消息和堆栈跟踪,以及任何额外的异常特定上下文信息.(但请注意,如果使用调试信息编译应用程序,堆栈跟踪将仅显示源文件和行号)

但值得注意的是,看到完整的堆栈跟踪对于用户来说可能是相当不合适的,所以只要有可能,您应该尝试处理异常并打印出更友好的错误消息.

另一方面 - 您应该WriteLogError使用功能齐全的日志框架(如Serilog)替换您的方法,而不是尝试编写自己的方法.

您的日志记录方法不是线程安全的(您的日志文件可能最终会将日志消息相互混合)并且如果您捕获异常,也绝对不应该调用自身 - 这将意味着在记录错误时发生的任何异常都可能导致难以诊断的StackOverflow异常.

我可以建议如何解决这些问题,但是如果使用适当的日志框架,你会得到更好的服务.

  • @davewasthere [Serilog](https://serilog.net/) 是我选择的新日志框架 (3认同)

Ste*_*dit 7

只要登录ToString().它不仅会为您提供堆栈跟踪,还会包含内部异常.

  • 请注意,如果他想要行号,他也需要分发调试符号(但我认为可以使用 ilmerge 将它们合并到 exe 中)。 (2认同)