Using NLog in an AspNetCore Environment
Introduction
In this example, we will see how to use NLog in an AspNetCore project. NLog is a widely used logging library for managing and recording logs in .NET applications, including ASP.NET Core. It is one of the most popular logging solutions due to its flexibility, ease of use, and configurability. Here’s how it works in ASP.NET Core:
-
Installation: To use NLog in an ASP.NET Core application, you first need to install the NLog.Web.AspNetCore NuGet package:
dotnet add package NLog.Web.AspNetCore -
Configuration: NLog configuration can be done either via an
nlog.configfile or programmatically in the code. Here’s an example of basic configuration using an XML file (nlog.config):<configuration> <targets> <target name="logfile" xsi:type="File" fileName="logs/logfile.txt" /> <target name="logconsole" xsi:type="Console" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="logfile,logconsole" /> </rules> </configuration> -
Configuration in Program.cs: To integrate NLog with ASP.NET Core, add the following code to
Program.cs:using NLog.Web; var builder = WebApplication.CreateBuilder(args); builder.Logging.ClearProviders(); builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Host.UseNLog(); // Add NLog to the logging var app = builder.Build(); -
Database Logging: NLog also supports logging to a database, which can be useful for keeping logs in a centralized database. To do this, you need to configure a database target. Here’s an example of how to configure database logging:
<!-- Log to database (SQL Server) --> <target name="database" xsi:type="Database" connectionString="${var:ConnectionStrings}"> <dbProvider>mssql</dbProvider> <commandText>INSERT INTO LogTable (Date, LevelLog, Message, Exception) VALUES (@date, @levelLog, @message, @exception);</commandText> <parameter name="@date" layout="${date}" /> <parameter name="@levelLog" layout="${level}" /> <parameter name="@message" layout="${message}" /> <parameter name="@exception" layout="${exception:format=ToString}" /> </target>To make this work, you need to download both the System.Data.SqlClient package and the NLog extension for the database:
dotnet add package System.Data.SqlClient dotnet add package NLog.DatabaseThe connection to the database must be set directly in Program.cs:
LogManager.Configuration.Variables["ConnectionStrings"] = "ConnString";You can also retrieve it directly from the
appsettings.jsonfile:"LogCustom": { "ConnectionString": "ConnString" }Then retrieve it inside the
nlog.configfile:<target name="database" xsi:type="Database" connectionString="${configsetting:item=LogCustom.ConnectionString}"> <dbProvider>mssql</dbProvider> <commandText>INSERT INTO LogTable (Date, LevelLog, Message, Exception) VALUES (@date, @levelLog, @message, @exception);</commandText> <parameter name="@date" layout="${date}" /> <parameter name="@levelLog" layout="${level}" /> <parameter name="@message" layout="${message}" /> <parameter name="@exception" layout="${exception:format=ToString}" /> </target>
In this way, we have configured a full-fledged logging system in an AspNetCore application. Each message, based on its level, will be logged according to the configurations set in the file.
Custom Target
In addition to the predefined targets, you can create a custom target for NLog. A custom target is a class that extends the base AsyncTaskTarget class and implements the WriteAsyncTask method to write logs to a custom source.
Here’s an example of a custom target that writes logs to a text file:
[Target("CustomFile")]
public class CustomFileTarget : AsyncTaskTarget
{
public CustomFileTarget()
{
FileName = "logs/customfile.txt";
}
protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
{
string logMessage = Layout.Render(logEvent);
await File.AppendAllTextAsync(FileName, logMessage, cancellationToken);
}
}To use the custom target, add it to the NLog configuration in the nlog.config file:
<target name="customfile" xsi:type="CustomFile">
<layout>${message}</layout>
</target>If the class is in another project, you need to add a reference to the project that contains the custom target in the nlog.config file:
<extensions>
<add assembly="CustomNLogTarget" />
</extensions>This way, you can create custom targets for NLog and configure them to write logs to any desired source.