NLog is a powerful and flexible logging library for .NET applications. It provides a simple, yet highly configurable way to log messages from your C# application. In this article, we will explore the basics of NLog, how to set it up in a C# project, and how to configure and use it for various logging scenarios.
Logging is an essential part of any application. It helps developers understand the internal workings of the application, track errors and exceptions, and monitor the overall health of the application. NLog stands out as a powerful logging solution for .NET applications due to its:
To get started with NLog in your C# project, you need to install the NLog NuGet package. You can do this using the Package Manager Console, the .NET CLI, or by adding the package via the NuGet Package Manager in Visual Studio.
Package Manager Console:
Install-Package NLog
.NET CLI:
dotnet add package NLog
Once the package is installed, you can start using NLog in your application.
NLog requires a configuration file to define its logging targets, rules, and layout. The most common way to configure NLog is using an XML file named NLog.config
. Create this file in the root of your project and set its “Copy to Output Directory” property to “Copy if newer”. The contents of the file should look like this:
<?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">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
In this example, we define a single target named “logfile” that writes log entries to a file called “file.txt”. We also set up a rule for all loggers to write log entries with a minimum level of “Info” to the “logfile” target.
Now that NLog is configured, you can start using it in your C# code. To do this, create an instance of the NLog.Logger
class and use its methods to log messages:
using NLog;
public class Program
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public static void Main(string[] args)
{
Logger.Info("Application started.");
try
{
// Your application logic here
}
catch (Exception ex)
{
Logger.Error(ex, "An error occurred.");
}
Logger.Info("Application stopped.");
}
}
The Logger
class provides various methods for logging messages with different severity levels, such as Trace
, Debug
, Info
, Warn
, Error
, and Fatal
.
NLog offers many advanced configuration options and features, such as multiple targets, custom layouts, filtering, and more. Here are some examples:
Multiple Targets:
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="console" xsi:type="Console" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
This configuration sends log entries with a minimum level of “Info” to afile, and log entries with a minimum level of “Debug” to the console.
Custom Layout:
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt">
<layout>${longdate} | ${logger} | ${uppercase:${level}} | ${message} ${exception:format=ToString}</layout>
</target>
</targets>
This configuration sets a custom log message layout that includes the date, logger name, log level, message, and exception information.
Filtering:
<rules>
<logger name="*" minlevel="Info" writeTo="logfile">
<filters>
<when condition="contains('${message}','FilterMeOut')" action="Ignore" />
</filters>
</logger>
</rules>
This configuration adds a filter that ignores log messages containing the text “FilterMeOut”.
Using NLog with Dependency Injection (ASP.NET Core):
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
loggingBuilder.AddNLog("nlog.config");
});
// Other service registrations...
}
}
This code snippet configures NLog to work with the built-in logging system in ASP.NET Core using dependency injection.
NLog is a powerful and flexible logging library that can greatly enhance your C# application’s logging capabilities. With its easy integration, rich configuration options, and support for various .NET platforms, NLog is an excellent choice for developers looking to improve their application’s logging infrastructure. Start using NLog in your C# projects today and experience the benefits of a modern, high-performance logging library.