Log exception to file in c# .net core application explained

In production environment when any bug gets reported at that time as developer wants to get the exception details of bug to resolve the issue on high priority.
In some case there might be situation where exception is not logged in table but developer wants to check the bug immediately. for that purpose we need to write the
exception details including stack trace of bug in file. To implement this easily i am going to demonstrate the implementation of custom logging in file as below.

First we need to construct the exception and logger method in custom logger class as shown below.

 public class CustomLogger  
      public static List<string> ConstructExceptionDetails(Exception ex,string FunctionName)  
       return new List<string>() {  
             $"{DateTime.Now} - {FunctionName}",  
             $"Exception: {ex.Message}",  
             $"StackTrace: {ex.StackTrace}",  
             $"InnerException: {ex.InnerException?.Message}",  
             string.Empty };  
  public static void WriteCustomLog(List<string> Logs,string FileName,string FilePath)  
         string filePath = FilePath;  
           filePath = PathToContentRoot();  
         File.AppendAllLines(Path.Combine(filePath, FileName), Logs);  

Once we create custom logger class we can use its method in the code in catch block to log quickly to files. The logger class writes the log with date time of each activities to get the details of exact exception, it also writes the inner exception as well as the stack trace of the exception which helps to dig in the exception occurred.

To use this logger class you can write code as stated below.

 public void Dividbyzero()  
           int div=5/0;  
       catch (Exception err)  
           var logText= CustomLogger.ConstructExceptionDetails(err,"devidbyzero");  

In above code we have called ConstructExceptionDetails method which formats the exception details to log to file. Next we have called writecustomlog !method which takes parameters like logtext, log file name, and path to store log.

That's it this is the useful logger code which can be used in projects to identify the exception details.

Happy coding, bug fixing !!!!


Popular posts from this blog

Restore the lost focus of Auto post back controls in asp.net update Panel control

Clone a generic list in C# using extension method

Add Comma automatically while entering amounts in textbox using Javascript

Disable backspace key using Jquery

Step by step migration of ASP.NET Core 2.2 to 3.1

How to Import CSV File and bind csv file data to gridview in asp.net using c#

Source Code Beautifier And Format Source Code For Blogger and Websites

Remove Owin from MVC 5 Application and use asp.net custom forms authentication

All about the IEnumerable VS IQueryable in c#