How to use Nlog in Blazor/Asp.net Core applications

Kevin (Xiaocong) Zheng
3 min readFeb 6, 2024

This document explains how to integrate and use NLog, a popular logging library, in your Blazor or ASP.NET Core applications.

1. Installation

  1. Add the NLog.Web.AspNetCore/NLog.Extensions.Logging/NLog.Database(if you want to store the log to your database instead of store them in files) package to your project using NuGet.
  2. Create a nlog.config file in the project under root folder, here is a example:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>

<!-- the targets to write to change the data table name and connection string to your actual one-->
<targets>
<target name="dbase" xsi:type="Database"
dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
connectionString="${configsetting:item=ConnectionStrings.DefaultConnection}">
<commandtext>INSERT INTO dbo.ExceptionLog (CreatedOn,Message,Level,Exception,StackTrace,Logger,Url) VALUES (@datetime,@msg,@level,@exception,@trace,@logger,@url)</commandtext>
<parameter name="@datetime" layout="${date}" />
<parameter name="@msg" layout="${message}" />
<parameter name="@level" layout="${level}" />
<parameter name="@exception" layout="${exception}" />
<parameter name="@trace" layout="${stacktrace}" />
<parameter name="@logger" layout="${logger}" />
<parameter name="@url" layout="${aspnet-request-url}" />
</target>

</targets>

<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Error" writeTo="dbase" />

<!--Output hosting lifetime messages to console target for faster startup detection -->
<!-- <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" /> -->

<!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
<!-- <logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="System.Net.Http.*" maxlevel="Info" final="true" />

<logger name="*" minlevel="Trace" writeTo="ownFile-web" /> -->
</rules>
</nlog>

2. Configuration

Modify and add nlog related service to program.cs file. Inject libs, put all the existing code to a huge try catch block(in case the nlog failed to start and break the whole application), and set the default log function to log Nlog’s exceptions.

Try Block

This is how we inject the Nlog’s services. And you can change the log level from information to critical(there are 5 levels in total).

Injection

This is the catch and finally part, how we deal with the Nlog’s exceptions.

Catch and Finally block

3. Using NLog

Once configured, you can use NLog to create loggers and write log messages throughout your application:

using NLog; We just need to inject a logger to our controller or service, and call the logger.log function to log exceptions

Examples:

public class MyController : Controller
{
private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
public IActionResult Index()
{
_logger.Info("Starting Index action");
// ... your code ...
return View();
}
}
Service Example

--

--