Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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#.
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.
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.
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:
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.
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.
Name the file nlog.config and click the "Add" button.
<?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>
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
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.
NLog supports several logging levels, each with its own significance:
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>
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
Our Program has logged messages in the Console as shown below.
Now, We have demonstrated the example of logging messages in the Console, Now we will configure NLog target to log messages in the 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>
Now, run the program to log messages in a file.
NLog supports various log output targets, allowing you to choose where your log messages should be stored. Some common targets include:
You can configure NLog to use one or more targets simultaneously.
Explore Further about 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 Conversion 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
Let's generate a PDF 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
The above code snippet will create a PDF file with a logged message in the file as shown below.
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 of IronPDF for testing its features. If it meets your requirements, you can opt for a commercial license for IronPDF, 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.
9 .NET API products for your office documents