NLog

Creates and manages instances of Logger objects.

Install from nuget: NLog 4.7.0

Configuration

  1. Create NLog.config with default template data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>

<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>

<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->

<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>

<rules>
<!-- add your logging rules here -->

<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
</nlog>

This came from:

  1. Set the file to always copy

Always Copy

  1. Configure the file
1
2
3
4
5
6
7
8
9
10
11
12
13
<targets>
<target name="logfile"
xsi:type="File"
archiveNumbering="Date"
archiveEvery="Day"
maxArchiveFiles="50"
bufferSize="102400"
fileName="appname.log" />
</targets>

<rules>
<logger name="*" writeTo="logfile" />
</rules>

Example use

1
2
3
4
5
6
7
var logger = NLog.LogManager.GetCurrentClassLogger();

logger.Debug("Some debug");
logger.Debug("Some other debug");
logger.Info("Some info.");

~ this will then create `appname.log` in your executing bin directory.

Configure for Dependency Injection

Install from nuget: NLog.Web.AspNetCore 4.9.2

  1. Update Program.cs

BEFORE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace GameUI
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}

AFTER

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using NLog.Web;
using Microsoft.Extensions.Logging;
using System;

namespace GameUI
{
public class Program
{
public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog(); // NLog: setup NLog for Dependency injection
}
}
}
  1. Configure appsettings.json

If you are debugging locally make the changes in appsettings.Development.json

The Logging configuration specified in appsettings.json overrides any call to SetMinimumLevel. So either remove "Default": or adjust it correctly to your needs. - github.com/NLog

BEFORE

1
2
3
4
5
6
7
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
}

AFTER

1
2
3
4
5
6
7
8
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information"
}
}
}
  1. Inject into your constructor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using Microsoft.Extensions.Logging;

public class ComputerMoveHard : IComputerMove
{
private readonly ILogger<ComputerMoveHard> _logger;

public ComputerMoveHard(ILogger<ComputerMoveHard> logger)
{
_logger = logger;
}

public int SetPosition(...)
{
_logger.LogTrace("This is LogTrace");
_logger.LogDebug("This is LogDebug");
_logger.LogInformation("This is LogInformation");
_logger.LogWarning("This is LogWarning");
_logger.LogError("This is LogError");
_logger.LogCritical("This is LogCritical");

Log Levels

These levels work from minimum (Trace) to maximum (Critical), so if you set your level to Information you will not get logs for Trace and Debug

1
2
3
4
5
6
7
Trace - Very detailed log messages, potentially of a high frequency and volume
Debug - Less detailed and/or less frequent debugging messages
Information - Informational messages
Warning - Warnings which don't appear to the user of the application
Error - Error messages
Critical - Fatal error messages. After a fatal error, the application usually terminates.
None - No logging

Logging To Different Files

You can specify logging to files by class and wildcard, super useful for debugging code flows. For the below I needed only logs for moverules from the name space GameEngine.Services.ComputerMove.MoveRules.*

So for the below I would include _logger.LogTrace("This is LogTrace"); in the code for the MoveRules classes and this data will go into moverules.log

Note that appsettings needs to then be set to Trace.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<targets>
<target name="moverules"
xsi:type="File"
archiveNumbering="Date"
archiveEvery="Day"
maxArchiveFiles="50"
bufferSize="102400"
fileName="moverules.log" />
<target name="tictactoe"
xsi:type="File"
archiveNumbering="Date"
archiveEvery="Day"
maxArchiveFiles="50"
bufferSize="102400"
fileName="tictactoe.log" />
</targets>

<rules>
<logger name="GameEngine.Services.ComputerMove.MoveRules.*" level="Trace" writeTo="moverules" />
<logger name="*" minlevel="Debug" writeTo="tictactoe" />
</rules>

References