Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging exception in c#

Tags:

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 
like image 691
happysmile Avatar asked Aug 16 '10 07:08

happysmile


People also ask

What is exception logging?

The exception log is a rolling collection of 4 files; when a file is full, data is added to the next file. When the last file has been filled, data starts to be added to the first file, overwriting the previous data there. This cycle of writing continues, ensuring that the newest data is retained.

What is logging exception in C#?

Monitoring the error of live application is very important to avoid any inconvenience, In C# to handle exception try ,catch ,finally keyword are used,so in this article we will learn how to catch the error and log error details to text file so developer can fix it as soon as possible.

What is exception handling and logging?

Logging and exception handling are like two peas in a pod. When a problem happens in your Java code, that typically means you have an exception that needs to be handled, and of course, any time an error or unanticipated event occurs, that occurrence should be logged appropriately.

What is logging exception in asp net?

ELMAH (Error Logging Modules and Handlers) is an error logging facility that you plug into your ASP.NET application as a NuGet package. ELMAH provides the following capabilities: Logging of unhandled exceptions. A web page to view the entire log of recoded unhandled exceptions.


2 Answers

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.

like image 127
Justin Avatar answered Nov 02 '22 03:11

Justin


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

like image 36
Steven Sudit Avatar answered Nov 02 '22 04:11

Steven Sudit