DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

Flexible Log Management with NLog

NLog is a powerful and flexible library for generating logs in .NET applications. It allows you to send logs to various destinations, such as files, databases, or consoles, with simple configuration. NLog is widely used for application monitoring and to help identify and diagnose issues. In this example, we will see how to configure and use NLog to generate logs in a file.

Libraries:

To use the NLog library, install the following NuGet packages in your project:

Install-Package NLog
Enter fullscreen mode Exit fullscreen mode

Example Code:

using NLog;
using System;

namespace NLogExample
{
    class Program
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            // Configuring NLog
            var config = new NLog.Config.LoggingConfiguration();

            // Target: file
            var logFile = new NLog.Targets.FileTarget("logFile") { FileName = "log.txt" };

            // Logging rules
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logFile);

            // Applying the configuration
            LogManager.Configuration = config;

            // Example logs
            logger.Info("The application has started.");
            logger.Warn("This is a warning.");
            logger.Error("An error occurred.");

            Console.WriteLine("Logs generated. Check the log.txt file.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we configure NLog to generate logs in a file called log.txt (path bin/Debug/net8.0/log.txt). First, we create a logging configuration, then specify that the logs will be saved to a file. We set logging rules to record messages from Info level to Fatal. After that, we use the logger to write three types of logs: Info, Warn, and Error. Finally, the logs are written to the file, and a message is displayed in the console indicating that the logs were successfully generated.

Conclusion:

NLog offers an easy and flexible solution for log management, allowing you to configure multiple targets and logging levels. It is an excellent tool for monitoring and debugging applications, helping you track errors and important events.

Code source: GitHub

Top comments (0)