I have 4+ experience and working as software Engineer with Hytech professionals India PVT ltd and also working as Consultant,Trainer,Blogger and Author on Microsoft technologies,Also I have Trained more than 500+ IT professionals.I have knowledge about Asp.net,C#,SQL,Project management,replication,MVC,WebApi,SSRS,PostMan,TFS,SVN,Swagger,WMI,Agile,SignalR,Angularjs,IIS configuration.

Part 35:: Global Exception Filter,Exception handling and logging using Log4Net in Web Api 2

In this article, I'll explain about the Global exception filter and discuss about the way to handle exception globally in whole project without using try catch .And also explaining how to use log4net to create a log file on your local machine .
In ASP.NET MVC applications, Exception handling taking care of is done generally in two ways: at simple level use try catch block in the code. ASP.NET MVC comes with some inbuilt features like as Exception Filter The HandleError is the default worked in Exception Filter. Sadly, the HandleError filter doesn't gives a complete response to the exception handling globally of issue and that makes us to at present depend on the Application_Error Event. 
 Some related links which may help to learn basic and advanced concepts related to this. 


Today we will learn these topics which are given below listed..
  1. How to use Exception filter?
  2. How to configure Log4Net in webapi 2?
  3. How to create Global Exception filter?
  4. How to avoid to use try catch in application? 
  5. How to create log file with log details in drive. 
  6. Advantage of Exception filter.
To learn these topics you should follow steps which are given below.
Step 1:- Create a web based application  in MVC or web Api.see image......
 According your thinking you can type your project name ,i have given "swaggerTsting".,Click on "OK".
Thereafter next window will be open ans select "MVC" OR "WebApi" otherwise both.and click on ok.
After that you can see you project in solution explorer.see image.

 In this you can see some apicontroller already created with demo output.you can create any number of controller and action.
If i'll run this application now so this application will be run correctly .
Now i am going to integrate Exception filter with log4net.so follow some steps....
Step 2:- Firstly add log4net in your solution using nuget package or PM console.
Just i am going to add log4net by PM console. see image...
According this image you can also add log4net,Thereafter click on "Package manager console " you will see new window on the bottom of editor.see image 
 Just type "Install-package log4net" or copy paste .
PM> Install-Package log4net 
Click enter and wait for 30 second ,log4net fill will be added  in your solution.you can check in solution explorer ,see image ....
 In this image you can see log4net will added and showing message in bottom pane.
Step 3:-After that create a folder in your application "ExLogger" its not mandatory but best way create a folder to put all file related to exception.
And create two file inside "ExLogger" folder
  1. log4net.config
  2. ExceptionManagerApi.cs 
you can see in image ....
Step 4:-Write custom code inside log4net.config file to set log path,log format,log type etc....
Log4net:- Copy this code and paste in your log4net.config file. 
  1. <log4net>  
  2.   <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">  
  3.     <!--  
  4.     The file location can be anywhere as long as the running application has read/write/delete access.  
  5.     The environment variable also can be set as the location.  
  6.     <file value="${TMP}\\Log4NetTest.log"/>  
  7.     -->  
  8.     <file type="log" value="D:\Logger.log"/>  
  9.     <appendToFile value="true"/>  
  10.     <rollingStyle value="Size" />  
  11.     <maxSizeRollBackups value="5" />  
  12.     <maximumFileSize value="5MB" />  
  13.     <!--Ensure the file name is unchanged-->  
  14.     <staticLogFileName value="true" />  
  15.     <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />  
  16.     <layout type="log4net.Layout.PatternLayout">  
  17.       <header value="Logging Start  
  18.   
  19. " />  
  20.       <footer value="Logging End  
  21.   
  22. " />  
  23.       <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>  
  24.     </layout>  
  25.     <!--<layout type="log4net.Layout.PatternLayout">  
  26.         <header value="[Header] 
  27.   
  28. " />  
  29.         <footer value="[Footer] 
  30.   
  31. " />  
  32.         <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />  
  33.       </layout>-->  
  34.   </appender>  
  35.   
  36.   <root>  
  37.     <!--  
  38.     1.OFF - nothing gets logged  
  39.     2.FATAL   
  40.     3.ERROR  
  41.     4.WARN  
  42.     5.INFO  
  43.     6.DEBUG  
  44.     7.ALL - everything gets logged  
  45.     -->  
  46.     <level value="ALL"/>  
  47.     <appender-ref ref="RollingFile"/>  
  48.   </root>  
  49. </log4net>  
 In this code you can change log format and destination path to save log details.
Step 5:-Now go to configure Exception filter logic in "ExceptionManagerApi.cs",copy and paste this code and in  your "ExceptionManagerApi.cs" file. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Web.Mvc;  
  7. using log4net;  
  8. using System.IO;  
  9. using System.Reflection;  
  10. using System.Web.Http.ExceptionHandling;  
  11.   
  12. namespace CrxApi.ExLogger  
  13. {  
  14.     public class ExceptionManagerApi : ExceptionLogger  
  15.     {  
  16.         ILog _logger = null;  
  17.         public ExceptionManagerApi()  
  18.         {  
  19.             // Gets directory path of the calling application  
  20.             // RelativeSearchPath is null if the executing assembly i.e. calling assembly is a  
  21.             // stand alone exe file (Console, WinForm, etc).   
  22.             // RelativeSearchPath is not null if the calling assembly is a web hosted application i.e. a web site  
  23.             var log4NetConfigDirectory = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;  
  24.   
  25.             //var log4NetConfigFilePath = Path.Combine(log4NetConfigDirectory, "log4net.config");  
  26.             var log4NetConfigFilePath = "c:\\users\\user\\documents\\visual studio 2012\\Projects\\ErrorLogingDummy\\ErrorLogingDummy\\ExLogger\\log4net.config";  
  27.             log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(log4NetConfigFilePath));  
  28.         }  
  29.         public override void Log(ExceptionLoggerContext context)  
  30.         {  
  31.             _logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);  
  32.             _logger.Error(context.Exception.ToString() + Environment.NewLine);  
  33.             //_logger.Error(Environment.NewLine +" Excetion Time: " + System.DateTime.Now + Environment.NewLine  
  34.             //    + " Exception Message: " + context.Exception.Message.ToString() + Environment.NewLine  
  35.             //    + " Exception File Path: " + context.ExceptionContext.ControllerContext.Controller.ToString() + "/" + context.ExceptionContext.ControllerContext.RouteData.Values["action"] + Environment.NewLine);   
  36.         }  
  37.         public void Log(string ex)  
  38.         {  
  39.             _logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);  
  40.             _logger.Error(ex);  
  41.             //_logger.Error(Environment.NewLine +" Excetion Time: " + System.DateTime.Now + Environment.NewLine  
  42.             //    + " Exception Message: " + context.Exception.Message.ToString() + Environment.NewLine  
  43.             //    + " Exception File Path: " + context.ExceptionContext.ControllerContext.Controller.ToString() + "/" + context.ExceptionContext.ControllerContext.RouteData.Values["action"] + Environment.NewLine);   
  44.         }  
  45.   
  46.     }  
  47.   
  48.   
  49.   
  50. }  
 In this i have configure my system path to set log4net setting ,you should change path according your application.
  1. var log4NetConfigFilePath = "c:\\users\\user\\documents\\visual studio 2012\\Projects\\ErrorLogingDummy\\ErrorLogingDummy\\ExLogger\\log4net.config";   
Change this according your application.
Step 6:-Now we need to configure "ExceptionManagerApi" class inside "WebApiConfig.cs" in app_start folder.
to make global we have to configure inside "WebApiConfig.cs". use this code inside "WebApiConfig.cs" and save.
  1. //Register Exception Handler  
  2.             config.Services.Add(typeof(IExceptionLogger), new ExceptionManagerApi());  
This code will use inside "Register" function.
Step 7:-If your application is now running good so to testing purpose throw any default exception and check.
see image.
 According this image i am throwing exception forcely .after that consume this api using postman or any other client .this action will be thorw exception and create and new log file in your system.
Step 8:- Run your application and use if any exception occurs anywhere ,any layer (BAL,DAL,....) exception wiil be manage by exception filter and create a new log file in your system by log4net.
No need to use other extra configuration to manage exception in your application. 
Advantage of Exception  Filter and Log4net.
  1. No need to use any complicated configuration.
  2. It will be manage global exception in your application. 
  3. No need to use try catch block .
  4. You can check log details from log file which is created by log4net
  5. We can find exact error on production server if exception will occur.
  6. Easy to impliment  in web api2.
  7. No need to manage exception on each layer ,because its for whole solution.
  8. Easy to maintenance .
You have just read an article that categorized by title MVC / WEB API by title Part 35:: Global Exception Filter,Exception handling and logging using Log4Net in Web Api 2. You can bookmark this page with a URL https://bikeshsrivastava.blogspot.com/2016/09/global-exception-filterexception.html. Thank You!
Author: Bikesh Srivastava - Sunday, 18 September 2016

There are currently no comments for "Part 35:: Global Exception Filter,Exception handling and logging using Log4Net in Web Api 2"

Post a Comment

Life Is Complicated, But Now programmer Can Keep It Simple.