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)  
     {  
       lock(obj)  
       {  
         string filePath = FilePath;  
         if(string.IsNullOrEmpty(FilePath))  
         {  
           filePath = PathToContentRoot();  
         }  
         if(!Directory.Exists(filePath))  
         {  
           Directory.CreateDirectory(filePath);  
         }  
         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()  
      {  
         try  
       {  
           int div=5/0;  
       }  
       catch (Exception err)  
       {  
           var logText= CustomLogger.ConstructExceptionDetails(err,"devidbyzero");  
           CustomLogger.WriteCustomLog(logText,"customLogger.txt","c:/Logs");  
       }  
      }  

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 !!!!

Comments

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Disable backspace key using Jquery

Devexpress Datebox date formatting in angular 6 with example