In this article, I'll explain about Global Exception Filter and discuss the ways to handle an exception globally in the whole project, without using try catch. I will also be explaining how to use log4net to create a log file on your local machine.
In ASP.NET MVC applications, Exception Handling is taken care of generally in two ways: at a simple level, and by using try catch block in the code. ASP.NET MVC comes with some in-built features, like as Exception Filter. The HandleErro the default in Exception Filter. Sadly, the HandleError filter doesn't give a complete response to the exception handling the issue globally. That makes us depend on the Application_Error Event, at present.

Some related links which may help to learn basic and advanced concepts related to this.
Today, we will learn these topics.
  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.



As per your choice, you can name your project. I have named it "swaggerTsting". Click on "OK". Thereafter, the next window will open. Select "MVC" OR "WebAPI" or both and click on OK.
After that, you can see your project in Solution Explorer.


Here, you can see some API Controllers already created with demo output. You can create any number of Controllers and Actions. If I run this application, it will run correctly.
Now, I am going to integrate Exception Filter with log4net. So, follow some steps....
Step 2 - First, add log4net in your Solution, using NuGet Package or PM console. I am going to add log4net by PM console.

Thereafter, click on "Package Manager Console ". You will see a new window on the bottom of editor, as shown below.

Just type "Install-package log4net" or copy paste .
PM> Install-Package log4net
Click enter and wait for 30 seconds. The log4net file will be added in your Solution. You can check that in Solution Explorer .



In this image, you can see that log4net is added and showing message in bottom pane.
Step 3 - After that, create a folder named "ExLogger" in your application. It's not mandatory but the best way to create a folder is to put all files related to exception and, create two files inside "ExLogger" folder.
  1. log4net.config
  2. ExceptionManagerApi.cs
You can see it in the following image.



Step 4 - Write custom code inside log4net.config file to set the log path, log format, and 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. <footer value="Logging End
  20. " />
  21. <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
  22. </layout>
  23. <!--<layout type="log4net.Layout.PatternLayout">
  24. <header value="[Header]
  25. " />
  26. <footer value="[Footer]
  27. " />
  28. <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
  29. </layout>-->
  30. </appender>
  31. <root>
  32. <!--
  33. 1.OFF - nothing gets logged
  34. 2.FATAL
  35. 3.ERROR
  36. 4.WARN
  37. 5.INFO
  38. 6.DEBUG
  39. 7.ALL - everything gets logged
  40. -->
  41. <level value="ALL"/>
  42. <appender-ref ref="RollingFile"/>
  43. </root>
  44. </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 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. namespace CrxApi.ExLogger
  12. {
  13. public class ExceptionManagerApi : ExceptionLogger
  14. {
  15. ILog _logger = null;
  16. public ExceptionManagerApi()
  17. {
  18. // Gets directory path of the calling application
  19. // RelativeSearchPath is null if the executing assembly i.e. calling assembly is a
  20. // stand alone exe file (Console, WinForm, etc).
  21. // RelativeSearchPath is not null if the calling assembly is a web hosted application i.e. a web site
  22. var log4NetConfigDirectory = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
  23. //var log4NetConfigFilePath = Path.Combine(log4NetConfigDirectory, "log4net.config");
  24. var log4NetConfigFilePath = "c:\\users\\user\\documents\\visual studio 2012\\Projects\\ErrorLogingDummy\\ErrorLogingDummy\\ExLogger\\log4net.config";
  25. log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(log4NetConfigFilePath));
  26. }
  27. public override void Log(ExceptionLoggerContext context)
  28. {
  29. _logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  30. _logger.Error(context.Exception.ToString() + Environment.NewLine);
  31. //_logger.Error(Environment.NewLine +" Excetion Time: " + System.DateTime.Now + Environment.NewLine
  32. // + " Exception Message: " + context.Exception.Message.ToString() + Environment.NewLine
  33. // + " Exception File Path: " + context.ExceptionContext.ControllerContext.Controller.ToString() + "/" + context.ExceptionContext.ControllerContext.RouteData.Values["action"] + Environment.NewLine);
  34. }
  35. public void Log(string ex)
  36. {
  37. _logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  38. _logger.Error(ex);
  39. //_logger.Error(Environment.NewLine +" Excetion Time: " + System.DateTime.Now + Environment.NewLine
  40. // + " Exception Message: " + context.Exception.Message.ToString() + Environment.NewLine
  41. // + " Exception File Path: " + context.ExceptionContext.ControllerContext.Controller.ToString() + "/" + context.ExceptionContext.ControllerContext.RouteData.Values["action"] + Environment.NewLine);
  42. }
  43. }
  44. }
In this, I have configured my system path to set log4net setting. You should change the path according your application.
  1. var log4NetConfigFilePath = "c:\\users\\user\\documents\\visual studio 2012\\Projects\\ErrorLogingDummy\\ErrorLogingDummy\\ExLogger\\log4net.config";
Change this according to 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 well, for testing purposes, throw any default exception and check.


According to this image, I am throwing exception forcibly. After that, consume this API using Postman or any other client. This action will throw an 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 managed 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 it's for whole solution.
  8. Easy maintenance of application.