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.
- Visual Studio 2019
- Razor Pages
- .Net Core 2.0
- NLog
- ASP.Net Core Web Application
- 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.

Add NLog related packages from NuGet into the solution
In Visual Studio Menu, browse to Tools - NuGet Package Manager - Package Manager Console.

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.






Join the conversation! Your thoughts help the community grow.