logging exception in c#

2019-02-04 10:54发布

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

5条回答
Animai°情兽
2楼-- · 2019-02-04 11:05

I find that the easiest way to log exceptions in C# is to call the ToString() method:

try
{

}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

This usually gives you all the information you need such as the error message and the stack trace, plus any extra exception specific context information. (however note that the stack trace will only show you source files and line numbers if you have your application compiled with debug information)

It is worth noting however that seeing a full stack trace can be fairly offputting for the user and so wherever possible you should try to handle exceptions and print out a more friendly error message.

On another note - you should replace your method WriteLogError with a fully featured logging framework (like Serilog) instead of trying to write your own.

Your logging method is not thread safe (your log file will probably end up with log messages being intermingled with each other) and also should definitely not call itself if you catch an exception - this will mean that any exceptions that occur whilst logging errors will probably cause a difficult to diagnose StackOverflow exception.

I could suggest how to fix those things, however you would be much better served just using a proper logging framework.

查看更多
再贱就再见
3楼-- · 2019-02-04 11:09

Just log ToString(). Not only will it give you the stack trace, but it'll also include the inner exceptions.

查看更多
我想做一个坏孩纸
4楼-- · 2019-02-04 11:18

I am only answering for the ask, other people have already mentioned about the code already. If you want the line number to be included in your log you need to include the generated debug files (pdb) in your deployment to the server. If its just your Dev/Test region that is fine but I don't recommend using in production.

查看更多
做自己的国王
5楼-- · 2019-02-04 11:21

Please note that the exception class is serializable. This means that you could easily write the exception class to disk using the builtin XmlSerializer - or use a custom serializer to write to a txt file for example.

Logging to output can ofcourse be done by using ToString() instead of only reading the error message as mentioned in other answers.

Exception class

https://docs.microsoft.com/en-us/dotnet/api/system.exception?redirectedfrom=MSDN&view=netframework-4.7.2

Info about serialization, the act of converting an object to a file on disk and vice versa.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/

查看更多
forever°为你锁心
6楼-- · 2019-02-04 11:22

Also, when you deploy a release build of your code to a production environment for instance, don't forget to include the .pdb files in the release package. You need that file to get the line number of the code that excepted (see How much information do pdb files contain? (C# / .NET))

查看更多
登录 后发表回答