.NET HELP

NLog C# (How it Works for Developers)

Published October 30, 2023
Share:

Logging is an essential aspect of software development. It helps developers track the behavior of their applications, troubleshoot issues, and gain insights into how their code is performing in various environments. NLog is a popular logging framework for C# that makes it easy to implement robust and flexible logging in your applications. In this comprehensive guide and tutorial, we will explore the world of NLog in C#.

What is NLog?

NLog is a free, open-source logging library for .NET and .NET Core applications. It provides a flexible and highly configurable way to log messages in your application. NLog is a widely used free logging platform in the .NET ecosystem due to its performance, extensibility, and ease of use.

Getting Started with NLog

We can use NLog in ASP.NET Web Applications, ASP.NET WEB APIs, Windows Form Applications, ASP.NET MVC Applications, or any kind according to our needs. We will use the Console Application to demonstrate all the use cases.

Install nLog Nuget Package

To get started with NLog, you'll need to install the NLog NuGet package in your project. You can do this via the NuGet Package Manager in Visual Studio by following the steps:

  1. In the "Tools" menu select "NuGet Package Manager," then choose "Manage NuGet Packages for Solution."
  2. Or, right-click on your project in the Solution Explorer, select "Manage NuGet Packages," and choose "Browse."
  3. In the NuGet Package Manager window, click on the "Browse" tab, and in the search box, type "NLog."
  4. You should see the NLog package in the search results. Click on it to select it.
  5. On the right side of the NuGet Package Manager window, there is a list of projects in your solution. Select the project(s) where you want to install NLog.
  6. Choose the desired version of the NLog package from the version dropdown. You can select the latest stable version or a specific version if needed.
  7. After selecting the project(s) and the version, click the "Install" button to start the installation process.

The NuGet Package Manager will download and install NLog and any dependencies. You will see the progress in the output window.

NLog is now successfully installed in your project, and you can start using it for logging within your C# code.

Create NLog Configuration file

To create an NLog configuration file (typically named nlog.config), you can follow these steps. This configuration file will specify how NLog should behave in your application, including log targets, layout renderers, and rules.

In your project, right-click on the project or the desired folder where you want to create the configuration file.

  1. Choose "Add" > "New Item..."
  2. In the "Add New Item" dialog, search for "XML File" or "XML" and select it.
  3. Name the file nlog.config and click the "Add" button.

  4. Open the newly created nlog.config file in a text editor or XML editor.
  5. Add the following configuration in the NLog.XML file. Below is a basic example of an NLog configuration that logs messages to a Console target. You can customize this Config File to suit your needs:

Config file

<?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">

  <!-- Define targets -->
  <targets>
    <!-- Log to a file -->
    <target name="console" xsi:type="Console" layout="${longdate}|${message}"/>
  </targets>

  <!-- Define rules -->
  <rules>
    <!-- All messages with a minimum log level of Debug or higher are written to the Console -->
    <logger name="*" minlevel="Debug" writeTo="Console" />
  </rules>

</nlog>
XML

In your C# code, make sure you load the NLog configuration from the nlog.config file. You typically do this in the application's startup code, such as in an ASP.NET Core Startup.cs(for .NET Version same or older than .NET 5), program.cs file (for .NET 6 or later version) or a console application's Main method:

internal class Program
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    static void Main(string [] args)
    {
        logger.Debug("This is Debug Message");
        Console.Read();
    }
}
internal class Program
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    static void Main(string [] args)
    {
        logger.Debug("This is Debug Message");
        Console.Read();
    }
}
Friend Class Program
	Private Shared logger As Logger = LogManager.GetCurrentClassLogger()
	Shared Sub Main(ByVal args() As String)
		logger.Debug("This is Debug Message")
		Console.Read()
	End Sub
End Class
VB   C#

The output of the above program is as:

In this example, we create an instance of the Logger class and use it to log messages at the Debug Level. Let's explore the tracing level supported by NLog.

Logging Levels

NLog supports several logging levels, each with its own significance:

  1. Trace: The most detailed level, typically used for diagnostic purposes.
  2. Debug: Used for debugging information that can be helpful during development.
  3. Info: General information about the application's operation.
  4. Warn: Indicates a potential issue that does not disrupt the application.
  5. Error: Indicates a failure that should be investigated but doesn't necessarily crash the application.
  6. Fatal: Indicates a critical failure that should be addressed immediately.

By categorizing log messages into these levels, you can easily filter and prioritize them based on their severity.

Set minlevel="Trace" in the rules tag in your nLog.Config file as shown below.

<rules>
  <!-- All messages with a minimum log level of Trace or higher are written to the Console -->
  <logger name="*" minlevel="Trace" writeTo="Console" />
</rules>
XML

Let's write a code to log messages of all tracing levels.

internal class Program
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    static void Main(string [] args)
    {
        logger.Trace("This is Trace Message");
        logger.Debug("This is Debug Message");
        logger.Info("This is Info Message");
        logger.Warn("This is Warning Message");
        logger.Error("This is Error Message");
        logger.Fatal("This is Fatal Message");
        Console.Read();
    }
}
internal class Program
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    static void Main(string [] args)
    {
        logger.Trace("This is Trace Message");
        logger.Debug("This is Debug Message");
        logger.Info("This is Info Message");
        logger.Warn("This is Warning Message");
        logger.Error("This is Error Message");
        logger.Fatal("This is Fatal Message");
        Console.Read();
    }
}
Friend Class Program
	Private Shared logger As Logger = LogManager.GetCurrentClassLogger()
	Shared Sub Main(ByVal args() As String)
		logger.Trace("This is Trace Message")
		logger.Debug("This is Debug Message")
		logger.Info("This is Info Message")
		logger.Warn("This is Warning Message")
		logger.Error("This is Error Message")
		logger.Fatal("This is Fatal Message")
		Console.Read()
	End Sub
End Class
VB   C#

Our Program has logged messages in the Console as shown below.

nlog log messages

Now, We have demonstrated the example of logging messages in the Console, Now we will configure NLog target to log messages in the file.

Log Message in File

We need to set a file target instead of a Console target in our config file for file logging.

  <targets>
  <target xsi:type="File" name="fileTarget" fileName="D:\Logs\mylog.txt" layout="${longdate} ${level:uppercase=true} ${message}" />
</targets>

<rules>
  <logger name="*" minlevel="Trace" writeTo="fileTarget" />
</rules>
XML

Now, run the program to log messages in a file.

Logging targets

NLog supports various log output targets, allowing you to choose where your log messages should be stored. Some common targets include:

  1. File: Logs messages to one or more files.
  2. Console: Logs messages to the console.
  3. Database: Logs messages to a database (SQL Server, MySQL, Oracle, PostgreSQL, etc.) table.
  4. Email: Sends log messages as emails.
  5. Event Log: Logs messages to the Windows Event Log.
  6. Custom Targets: You can create custom log targets to fit your specific needs.

You can configure NLog to use one or more targets simultaneously.

Introducing IronPDF

IronPDF is a powerful .NET library that simplifies PDF handling in C# and VB.NET applications. It provides robust capabilities for creating, editing, and manipulating PDF documents, as well as converting HTML content to PDF format, making it an essential tool for developers across a wide range of industries, including web development, reporting, and document management.

IronPDF’s standout feature is its HTML to PDF function, which keeps your layouts and styles preserved. It generates PDFs from web content, making it ideal for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be easily converted to PDFs.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

Let's generate a PDF with logging.

PDF Generation with Logging

The first step is to install the IronPDF library into our project. We can do this using the NuGet Package Manager in Visual Studio or via the NuGet CLI. Open your project and write the following command in the Package Manager Console.

Install-Package IronPdf

This command will install IronPDF with all required dependencies in our project.

Write the following code to generate a PDF File from HTML with logging.

private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string [] args)
{
    logger.Info("Initializing Chrome PDF Renderer");
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    logger.Info("Creating PDF From HTML String");
    var pdf = renderer.RenderHtmlAsPdf("<h1>This is my Sample PDF<h1>");
    logger.Info("Saving PDF File");
    pdf.SaveAs(@"D:\myPDF.pdf");
}
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string [] args)
{
    logger.Info("Initializing Chrome PDF Renderer");
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    logger.Info("Creating PDF From HTML String");
    var pdf = renderer.RenderHtmlAsPdf("<h1>This is my Sample PDF<h1>");
    logger.Info("Saving PDF File");
    pdf.SaveAs(@"D:\myPDF.pdf");
}
Private Shared logger As Logger = LogManager.GetCurrentClassLogger()
Shared Sub Main(ByVal args() As String)
	logger.Info("Initializing Chrome PDF Renderer")
	Dim renderer As New ChromePdfRenderer()
	logger.Info("Creating PDF From HTML String")
	Dim pdf = renderer.RenderHtmlAsPdf("<h1>This is my Sample PDF<h1>")
	logger.Info("Saving PDF File")
	pdf.SaveAs("D:\myPDF.pdf")
End Sub
VB   C#

The above code snippet will create a PDF file with a logged message in the file as shown below.

Log and PDF File

Conclusion

In conclusion, NLog has emerged as an essential tool for effective logging in C# applications, offering developers a robust framework for capturing, categorizing, and managing log data. Its flexibility and ease of use make it a go-to choice for logging needs across various domains. Furthermore, when combined with complementary libraries like IronPDF, which simplifies PDF generation and manipulation in .NET applications, developers can extend their management capabilities to encompass the creation of PDF-based logs and reports. It's worth mentioning that IronPDF offers a free trial for testing its features. If it meets your requirements, you can opt for a commercial license, providing continued access to IronPDF's capabilities with added benefits and support for seamless integration into your projects, especially for PDF-related functionalities.

By employing the power of NLog and IronPDF together, developers can not only gain insights into their application's behavior but also enhance their reporting and document management processes, ensuring that their software remains efficient, maintainable, and well-documented structured logging.

< PREVIOUS
C# Ref Keywords (How it Works for Developers)
NEXT >
Entity Framework C# (How it Works for Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >