Simple global exception logger for asp.net core

By | August 9, 2018

I am sure many companies are slowly doing the migration from web forms in asp.net to MVC with asp.net core and with that migration comes the need for diagnostics or exception logger.  In this article is a very simple example for exception logging.

.Net Core has an entire comprehensive framework around logging which I will not be covering. If you want a simple example that will allow you to log unhandled exceptions in your .net core application then this post is for you.

Create your global exception logger.

First we create our global exception logger. Its pretty simple and all you have to do is to derive from IExceptionFilter and implement the interface. This is just a example, you will need to provide your own logging storage mechanism as the file approach is not good enough. Note the additional constructor that I added. If you where implementing your own logging provider then this is where it would plug in.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Mywebsite
{
public class GlobalExceptionLogger : IExceptionFilter
{
private string LogFile = "Log.txt";

public GlobalExceptionLogger(ILoggerFactory loggerFactory)
{
// Nothing todo
}

public void OnException(ExceptionContext context)
{
String ErrorInfo = String.Format("{0}//r/n{1}//r/n", context.Exception.Message, context.Exception.StackTrace);
System.IO.File.AppendAllText(LogFile, ErrorInfo);
}
}
}

Integrate your global exception logger.

In the ConfigureServices method of the Startup.cs file add the following code. The sample below is what it would look like if you started with a new asp.net core MVC website and added the GlobalExceptionLogger.

public void ConfigureServices(IServiceCollection services)
{
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

LoggerFactory logger = new LoggerFactory();

services.AddMvc().AddMvcOptions(o => o.Filters.Add(new GlobalExceptionLogger(logger)))
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

}

Thats it! Whenever an unhandled exception occurs the GlobalExceptionLogger will be called and you can write it to what ever storage you need to.

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of