问题
The NLog documentation explains how to configure NLog for .NET Core applications by using an nlog.config
XML file. However, I'd prefer to have just one configuration file for my application - appsettings.json
. For .NET Framework apps, it's possible to put the NLog configuration in app.config
or web.config
. Is it possible to put the NLog config in appsettings.json
in the same way?
For example, how could I put this configuration example from the NLog documentation for ASP.NET Core 2 into appsettings.json
?
<?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"
internalLogLevel="Info"
internalLogFile="c:\temp\internal-nlog.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" 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}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
回答1:
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
回答2:
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"
}
]
}
来源:https://stackoverflow.com/questions/56246416/how-can-i-configure-nlog-in-net-core-with-appsettings-json-instead-of-an-nlog-c