NLog provides consistent logging capabilities across various .NET application types including console apps, WinForms, and WPF. This demonstrasion uses a .NET 5 console application.
1. Adding NLog Dependency
There are two approaches to include NLog in your project:
- Install via NuGet package manager
- Directly reference the NLog.dll assembly
2. Configuration Setup
Create an NLog.config file in your project with the folllowing properties:
- Set 'Copy to Output Directory' to 'Copy if newer'
- Configure logging targets and rules as shown:
<?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"
autoReload="true"
throwExceptions="false">
<targets>
<target name="logfile"
xsi:type="File"
fileName="${basedir}/logs/app.log"
archiveAboveSize="1048576"
maxArchiveFiles="5"
layout="${longdate} | ${level} | ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
3. Logger Implementation
Create a wrapper class for simplified logging operations:
public static class AppLogger
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
public static void Initialize(string configPath)
{
if (!File.Exists(configPath))
throw new FileNotFoundException("NLog configuration missing");
LogManager.LoadConfiguration(configPath);
}
public static void LogDebug(string message) => _logger.Debug(message);
public static void LogInformation(string message) => _logger.Info(message);
public static void LogWarning(string message) => _logger.Warn(message);
public static void LogError(string message) => _logger.Error(message);
public static void LogCritical(string message) => _logger.Fatal(message);
}
4. Usage Example
static void Main()
{
var configPath = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"NLog.config");
AppLogger.Initialize(configPath);
AppLogger.LogDebug("Debug message");
AppLogger.LogInformation("Information message");
AppLogger.LogWarning("Warning message");
AppLogger.LogError("Error message");
LogManager.Shutdown();
}