NLog文档说明了如何使用nlog.config
XML文件为.NET Core应用程序配置NLog。但是,我希望为我的应用程序只有一个配置文件-appsettings.json
。对于.NET Framework应用程序,可以将NLog配置放在app.config
或web.config
中。是否可以通过相同的方式将NLog配置放入appsettings.json
中?
例如,如何将这个配置示例从NLog documentation for ASP.NET Core 2放入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>
答案 0 :(得分:2)
是的,这是可能的,但是具有最低版本要求。您必须使用 NLog.Extensions.Logging> = 1.5.0 。请注意,对于ASP.NET Core应用程序,如果您安装 NLog.Web.AspNetCore> = 4.8.2 。它将作为依赖项安装。
然后您可以在NLog
中创建一个appsettings.json
部分,并使用以下代码加载它:
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"));
例如,对于ASP.NET Core应用程序,您在Main()
中的Program.cs
方法应如下所示:
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();
}
}
可以使用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"
}
]
}
编辑:感谢Rolf Kristensen(首先为NLog开发了此功能!)指出了此Wiki页面,并提供了有关此功能的更多文档:https://github.com/NLog/NLog.Extensions.Logging/wiki/Json-NLog-Config
答案 1 :(得分:2)
添加到Rolf Kristensen的回复
带有数据库目标的appsettings.json。
"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"
}
]
}
答案 2 :(得分:0)
当你有一个控制台应用程序时,你可以这样做(我使用的是 Net 5):
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
...
}).ConfigureLogging((hostContext, logBuilder) =>
{
logBuilder.AddNLog(new NLogLoggingConfiguration(hostContext.Configuration.GetSection("NLog"))).SetMinimumLevel(LogLevel.Trace);
})
.UseConsoleLifetime();