Logging exceptions in ASP NET Core



In this video we will discuss how to log our own messages, warnings and exceptions using the ILogger interface provided by ASP.NET Core.

Text version of the video
https://csharp-video-tutorials.blogspot.com/2019/05/logging-exceptions-in-aspnet-core.html

Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1

Slides
https://csharp-video-tutorials.blogspot.com/2019/05/logging-exceptions-in-aspnet-core-slides.html

ASP.NET Core Text Articles & Slides
https://csharp-video-tutorials.blogspot.com/2019/01/aspnet-core-tutorial-for-beginners.html

ASP.NET Core Tutorial
https://www.youtube.com/playlist?list=PL6n9fhu94yhVkdrusLaQsfERmL_Jh4XmU

Angular, JavaScript, jQuery, Dot Net & SQL Playlists
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

If there are exceptions, while users are using our application we need to log the exceptions somewhere. A developer can then review the exception log and provide a fix if required. Logging exceptions is required to know what exceptions are occuring on production server as the application is being used.

Two simple steps to log your own custom messages, warnings or exceptions

Inject an instance of ILogger where you need the logging functionality

The type of the class or controller into which ILogger is injected can be specified as the argument for the generic parameter of ILogger. We do this because, the fully qualified name of the class or the controller is then included in the log output as the log category. Log category is used to group the log messages.

Since we have specified the type of ErrorController as the generic argument for ILogger, the fully qualified name of ErrorController is also included in the log output below.

private readonly ILogger[ErrorController] logger;

public ErrorController(ILogger[ErrorController] logger)
{
this.logger = logger;
}

LogError() method logs the exception under Error category.

logger.LogError($”The path {exceptionHandlerPathFeature.Path} ” +
$”threw an exception {exceptionHandlerPathFeature.Error}”);

LogWarning() method logs the message under Warning category.

In a real world application we usually log the exceptions and warnings to a database table, event viewer or a file. We will discuss logging to a file in our next video.

Comments are closed.