How can I configure NLog in .NET Core with appsettings.json instead of an nlog.config file?
Yes, this is possible but has a minimum version requirement. You must be using NLog.Extensions.Logging >= 1.5.0. Note that for ASP.NET Core applications this will be installed as a dependency if you install NLog.Web.AspNetCore >= 4.8.2.
You can then create an NLog
section in appsettings.json
and load it with the following code:
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
NLog.Config.LoggingConfiguration nlogConfig = new NLogLoggingConfiguration(config.GetSection("NLog"));
For example, for an ASP.NET Core application, your Main()
method in Program.cs
should look something like this:
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));
var logger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger();
try
{
logger.Debug("Init main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "Stopped program because of exception");
}
finally {
LogManager.Shutdown();
}
}
A configuration like the one in the question can be achieved with the following settings in appsettings.json
:
"NLog":{
"internalLogLevel":"Info",
"internalLogFile":"c:\\temp\\internal-nlog.txt",
"extensions":{
"NLog.Web.AspNetCore":{
"assembly":"NLog.Web.AspNetCore"
}
},
"targets":{
"allfile":{
"type":"File",
"fileName":"c:\\temp\\nlog-all-${shortdate}.log",
"layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
},
"ownFile-web":{
"type":"File",
"fileName":"c:\\temp\\nlog-own-${shortdate}.log",
"layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}"
}
},
"rules":[
{
"logger":"*",
"minLevel":"Trace",
"writeTo":"allfile"
},
{
"logger":"Microsoft.*",
"maxLevel":"Info",
"final":"true"
},
{
"logger":"*",
"minLevel":"Trace",
"writeTo":"ownFile-web"
}
]
}
Edit: Thanks to Rolf Kristensen (who developed this functionality for NLog in the first place!) for pointing out this wiki page with more documentation on this feature: https://github.com/NLog/NLog.Extensions.Logging/wiki/Json-NLog-Config
Adding to Rolf Kristensen's response.
appsettings.json with database target.
"NLog": {
"autoReload": true,
"throwConfigExceptions": true,
"internalLogLevel": "info",
"internalLogFile": "c:\\temp\\internal-nlog.txt",
"extensions": {
"NLog.Extensions.Logging": {
"assembly": "NLog.Extensions.Logging"
}
},
"targets": {
"database": {
"type": "Database",
"commandText": "INSERT INTO dbo.log (MachineName,Logged,Level,Message,Logger,Callsite,Exception) values (@MachineName,@Logged,@Level,@Message,@Logger,@Callsite,@Exception)",
"parameters": [
{
"name": "@MachineName",
"layout": "${machinename}"
},
{
"name": "@Logged",
"layout": "${date}"
},
{
"name": "@Level",
"layout": "${level}"
},
{
"name": "@Message",
"layout": "${message}"
},
{
"name": "@Logger",
"layout": "${logger}"
},
{
"name": "@Callsite",
"layout": "${callsite}"
},
{
"name": "@Exception",
"layout": "${exception:tostring}"
}
],
"dbProvider": "System.Data.SqlClient",
"connectionString": "Data Source=database server;Initial Catalog=database ;Trusted_Connection=False; User Id=AppUser;Password=AppUserPassword;"
}
},
"rules": [
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "database"
}
]
}