Logging Errors And Information Using NLog In .NET Core 2 Razor Pages

In this article, I will provide information on how to log errors, traces, and information using a third party tool named NLog in Razor pages. I am writing this article because I was not able to find any perfect article out there providing straight steps to implement logging in .NET Core Razor Pages. In order to see how to create a .NET Core web application with Razor Pages and retrieve data from SQL Server using Entity Framework, you can visit my previous article.
 
Below are the software/concepts used in this document.
  1. Visual Studio 2019
  2. Razor Pages
  3. .Net Core 2.0
  4. NLog
  5. ASP.Net Core Web Application
  6. C# Language

Introduction

 
As a developer, it is very important for us to have exceptions and errors logged somewhere so that we can find the reason for the error. There are multiple ways to achieve the logging in .NET Core web applications but we would be using NLog third-party tool for logging. The reason is that NLog has proven to be the fastest among various other tools out in the market. Below is the step-by-step description on how to achieve this in .Net Core Razor Pages.
 

Open your project in Visual Studio 2019

 
In my case, I am opening the earlier created project where Razor pages are present.
 
Logging Errors And Information Using NLog In .NET Core 2 Razor Pages
 

Add NLog related packages from NuGet into the solution

 
In Visual Studio Menu, browse to Tools - NuGet Package Manager - Package Manager Console.
 
Logging Errors And Information Using NLog In .NET Core 2 Razor Pages
 
Then execute below two commands to install the NLog packages,
 
“Install-Package NLog”
“Install-Package NLog.Web.AspNetCore
 

Create the XML Configuration file containing the NLog Settings

 
NLog tool internally uses the config file to define various properties. The important parts in this config XML file are:
  • internalLogFile — place where any issue with NLog would be logged.
  • extensions — a place to put the assemblies that NLog will use. Since we are using NLog in the .NET Core application; here, I have to add ASPNetCore assembly.
  • targets — a place to define where the log event will go.
  • rules — place to define what log events would be dispatched to the targets. The rules element maps the target with log level using logger element. The logger element has the following attributes.
    • name – the name of logger pattern
    • minlevel – minimal log level
    • maxlevel – maximum log level
    • level – single log level
    • levels - comma separated list of log levels
    • writeTo – comma separated list of targets to write to
    • final – no rules are processed after a final rule matches
    • enabled - set to false to disable the rule without deleting it
Below is the example XML config file that I am using in my application. Each target element represents the place where log events will go.
 
Here, in my example, I am putting logs to Windows Event Logs and file.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <nlog autoReload="true"  
  3.       xmlns="http://www.nlog-project.org/schemas/NLog.xsd"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.       internalLogLevel="info" internalLogFile="internalLog.txt">   
  5.   
  6.   <extensions>  
  7.     <add assembly="NLog.Web.AspNetCore" />  
  8.   </extensions>  
  9.     
  10. <targets>  
  11.     <target xsi:type="EventLog"  
  12.                 name="eventlog"  
  13.                 source="DotNetApp"  
  14.                 layout="${message}${onexception:${newline}${exception:format=ToString}}">  
  15.     </target>  
  16.       
  17. <target xsi:type="File"  
  18.             name="file"  
  19.             layout="${longdate} - ${level:uppercase=true} - ${logger}: ${message}${onexception:${newline}${exception:format=ToString}}"  
  20.       fileName="${basedir}\logs\DotNetApp.${shortdate}.log"  
  21.       keepFileOpen="false"  
  22.             encoding="utf-8"  
  23.       archiveFileName="DotNetApp.${shortdate}.log"  
  24.       archiveNumbering="Sequence"  
  25.       archiveEvery="Day"  
  26.       maxArchiveFiles="1"  
  27.       />  
  28.   </targets>  
  29.     
  30. <rules>  
  31.     <logger name="*" minlevel="Error" writeTo="eventlog" />  
  32.     <logger name="Microsoft.*" maxLevel="Info" final="true" />  
  33.     <logger name="*" minlevel="Info" writeTo="file" />  
  34.   </rules>  
  35. </nlog>  
 

Add NLog xml config file to the solution

 
Add the file to the root level of the project. And this file should always be available at a place where the project's dll is present. Therefore, we need to enable the "copy to bin" folder.
 
Logging Errors And Information Using NLog In .NET Core 2 Razor Pages
 

Initialize NLog Logging in the .Net Core Web Application.

 
To Initialize the NLog logging, open Startup.cs file from solution and add below code in the “Configure” Method,
  1. // --- Code for using the Nlog for writting logs  
  2.             env.ConfigureNLog("Nlog.config");  
  3.             loggerFactory.AddNLog();  

Logging Errors And Information Using NLog In .NET Core 2 Razor Pages

Consume NLog logging in Razor Pages.

 
To consume the NLog logging in Razor Page, here I am opening CreateModel.cshtml.cs file from solution and adding below code.
  1. //--- Code for getting the properties of the logged in user from AD  
  2. public class CreateModel : PageModel  
  3.     {  
  4.         private readonly ILogger<CreateModel> _logger;  
  5.         public CreateModel(ILogger<CreateModel> logger)  
  6.         {  
  7.             _logger = logger;  
  8.         }  
  9.   
  10.         public IActionResult OnGet()  
  11.         {  
  12. try{  
  13.             _logger.LogInformation("This is NLog logging");  
  14.             return Page();  
  15. }catch(Exception ex)  
  16. { _logger.LogError(ex.Message); }  
  17.         }  
  18.     }  
Logging Errors And Information Using NLog In .NET Core 2 Razor Pages
 
Test the files by browsing to the CreateModel page. Then we can browse to the log file. In my example, my file is present in below path:
 
Project folder - bin - Debug - netcoreapp2.1 - logs
 
Logging Errors And Information Using NLog In .NET Core 2 Razor Pages
 
Open the file and you would find the information that we logged from the OnGet method in CreateModel Razor Page.
 
Logging Errors And Information Using NLog In .NET Core 2 Razor Pages
 
That is it. I hope you have learned something new from this article and will utilize this in your work.


Similar Articles