NLog for C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

NLog for C# (.NET): Complete Guide with Examples

\n\n

Welcome to the detailed guide on the NLog library for the .NET platform. NLog is a powerful, flexible, and high-performance logging system that has become the de facto standard for many .NET projects. In this article, we will cover everything: from installation to advanced techniques, with real code examples and optimization tips.

\n\n

1. What is NLog and why is it needed?

\n\n

NLog (short for ".NET Logging") is a free, open-source library for the .NET platform, designed for flexible and efficient logging. It allows developers to write diagnostic information (logs) to various destinations: files, console, databases, network sockets, monitoring systems (e.g., Seq, Elasticsearch, Sentry), and many others.

\n\n

Why is logging necessary? In modern software development, logs are the application's "black box." Without them, it's impossible to understand why a server crashed, where an error occurred, or what data was being processed at the time of failure. NLog solves this problem by providing:

\n
    \n
  • Routing flexibility: You can configure different logging levels (Trace, Debug, Info, Warn, Error, Fatal) for different parts of the application.
  • \n
  • Performance: Asynchronous writing, lazy initialization, minimal impact on speed.
  • \n
  • Extensibility: Hundreds of ready-made targets and the ability to write your own.
  • \n
  • Configuration without recompilation: Settings can be changed on the fly via XML, JSON, or code.
  • \n
\n\n

NLog is ideal for: web applications (ASP.NET Core), console utilities, microservices, desktop applications (WPF/WinForms), and background services (Windows Services, Worker Services).

\n\n

2. Installation

\n\n

NLog is installed via the NuGet package manager. Run one of the following commands in the Visual Studio Package Manager Console or in the .NET CLI terminal:

\n\n
// Via .NET CLI (recommended)\ndotnet add package NLog\n\n// Via Package Manager Console\nInstall-Package NLog\n\n// For ASP.NET Core, it is also recommended to install the integration:\ndotnet add package NLog.Web.AspNetCore
\n\n

After installation, you will need to create a configuration file nlog.config in the project root (or configure NLog programmatically).

\n\n

3. Quick Start — Minimal Working Example

\n\n

Create a console application and add the nlog.config file (right-click on the project → Add → New Item → XML File → name it nlog.config). Paste the following into it:

\n\n
<?xml version="1.0" encoding="utf-8" ?>\n<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"\n      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n\n    <!-- Target: where to write logs -->\n    <targets>\n        <target name="console" xsi:type="Console" layout="${longdate} | ${level:uppercase=true} | ${message} ${exception:format=ToString}" />\n        <target name="file" xsi:type="File" fileName="${basedir}/logs/app-${shortdate}.log"\n                layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message} ${exception:format=ToString}" />\n    </targets>\n\n    <!-- Routing rules -->\n    <rules>\n        <logger name="*" minlevel="Debug" writeTo="console,file" />\n    </rules>\n</nlog>
\n\n

Now let's write the code in Program.cs:

\n\n
using NLog;\n\npublic class Program\n{\n    // Create a logger for the current class\n    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();\n\n    public static void Main(string[] args)\n    {\n        Logger.Info("Application started");\n        \n        try\n        {\n                    

Recommendations