-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Getting started with .NET Core 2 Console application
Explains how to setup NLog as logging provider for .NET Core and Microsoft Extension Logging (MEL).
ℹ️ See also example in GitHub
Notice that NLog can be used on .NET Core without help from Microsoft Extension Logging and NLog.Extension.Hosting. See standard NLog Tutorial.
In Visual Studio 2017, using .NET 4.6.1+ or .NET Core 2
Install:
- The package NLog.Extensions.Logging
- The package Microsoft.Extensions.DependencyInjection - or use another DI library.
- The package Microsoft.Extensions.Configuration.Json (used in Main method
SetBasePath
+AddJsonFile
) - Update the NLog package if possible
e.g.
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
<PackageReference Include="NLog" Version="4.6.5" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.5.1" />
</ItemGroup>
Create nlog.config (lowercase all) file in the root of your application project (File Properties: Copy Always)
We use this example:
<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="c:\temp\console-example-internal.log"
internalLogLevel="Info" >
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log"
layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
<target xsi:type="Console" name="logconsole"
layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile,logconsole" />
</rules>
</nlog>
It is recommended to read the NLog Tutorial. For more detailed information about config file can be found here.
If you like to include other targets or layout renderers, check the Platform support.
Ensure to configure your project-file to copy NLog.config to the output directory:
<ItemGroup>
<None Update="nlog.config" CopyToOutputDirectory="Always" />
</ItemGroup>
public class Runner
{
private readonly ILogger<Runner> _logger;
public Runner(ILogger<Runner> logger)
{
_logger = logger;
}
public void DoAction(string name)
{
_logger.LogDebug(20, "Doing hard work! {Action}", name);
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
static void Main(string[] args)
{
var logger = LogManager.GetCurrentClassLogger();
try
{
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory()) //From NuGet Package Microsoft.Extensions.Configuration.Json
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
using var servicesProvider = new ServiceCollection()
.AddTransient<Runner>() // Runner is the custom class
.AddLogging(loggingBuilder =>
{
// configure Logging with NLog
loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
loggingBuilder.AddNLog(config);
}).BuildServiceProvider();
var runner = servicesProvider.GetRequiredService<Runner>();
runner.DoAction("Action1");
Console.WriteLine("Press ANY key to exit");
Console.ReadKey();
}
catch (Exception ex)
{
// NLog: catch any exception and log it.
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)
LogManager.Shutdown();
}
}
On screen:
In file:
2017/10/16 23:08:46.479|DEBUG|Doing hard work! Action1 |ConsoleExample.Runner|Action=Action1, EventId_Id=20, EventId_Name=, EventId=20
If you need a minimal solution, e.g. for a simple console application, and there is no need to use dependency injection, you can create a Microsoft Extensions Logging compatible logger with a single line of code. For example, this is useful in cases where you call existing libraries that take such a logger as a parameter, and you still want to use the power of NLog.
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ConsoleExample
{
internal static class Program
{
private static void Main()
{
var logger = LoggerFactory.Create(builder => builder.AddNLog()).CreateLogger<Program>();
logger.LogInformation("Program has started.");
Console.ReadKey();
}
}
}
See also: NLog GetCurrentClassLogger and Microsoft ILogger
Next step, see Configure NLog with nlog.config
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
- Articles about NLog
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json