1、安裝Nuget包:
NLog;
NLog.Web.AspNetCore;
NLog.Mongo;
NLog.WindowsIdentity;
NLog.WindowsIdentity不一定需要,如果運作時報異常(如果配置檔案中throwException設定為false,不會報異常):找不到“windows-identity”就需要安裝這個包。
2、配置檔案:
<?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"
throwExceptions="true"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- enable mongodb layout renderers -->
<extensions>
<add assembly="NLog.WindowsIdentity"/>
<add assembly="NLog.Mongo"/>
</extensions>
<targets>
<!-- write log to mongodb-->
<target xsi:type="Mongo"
name="mongo" databaseName="TestLog"
collectionName="Logs"
connectionString="mongodb://tang:[email protected]:27017/TestLog"
IncludeDefaults="false"
>
<Field name="Date" layout="${date:format=yyyy-MM-dd HH\:mm\:ss}" />
<Field name="Level" layout="${level}" />
<Field name="Logger" layout="${logger}"/>
<Field name="Message" layout="${message}" />
<Field name="Exception" layout="${exception:format=tostring}" />
<Field name="CallSite" layout="${callsite:filename=true}"/>
<Field name="StackTrace" layout="${stacktrace}"/>
</target>
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Trace" writeTo="mongo"/>
</rules>
</nlog>
這裡有幾個需要注意的地方:
(1)NLog中預設沒有MongoDB的 layout renderers,需要單獨引入,即上面的
<extensions>...</extensions>
(2)配置MongoDB時,若不加“IncludeDefaults=false”,不寫Field,就會在MongoDB中應用預設集合,包含“ID”,“Date”,“Logger”,“Exception”等。
設定IncludeDefaults=false,然後通過自定義Field,自定義MongoDB集合中顯示的内容。更具體的可以檢視GitHub上的NLog.Mongo的源碼,dalao的代碼寫得非常清晰:
https://github.com/loresoft/NLog.Mongo
(3)Field Date中,date預設為string類型,可以加
bsonType=DateTime
将其設定為DateTime類型。但是這裡的DateTime為國際标準時間,與中原標準時間相差8小時,而且format格式有問題,比如我設定了年月日 時分秒格式,最後輸出的時間還是帶毫秒的,隻不過毫秒位置都是0。如果用預設的string格式,輸出的是系統時間,且格式化有效,但是反序列化時,隻能反序列化為string類型,反序列為DateTime類型會報錯。
(4)其它配置内容可以參考官方配置文檔:
https://nlog-project.org/config/
3、調用:
Program.cs
using NLog.Web;
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog();
Startup.cs
using NLog.Extensions.Logging;
using NLog.Web;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//使用NLog作為日志記錄工具
loggerFactory.AddNLog();
//引入Nlog配置檔案,這裡配置檔案在項目根目錄下
env.ConfigureNLog("NLog.config");
app.UseMvc();
}
在其它類中記錄日志:
private readonly Logger nlog = LogManager.GetCurrentClassLogger();
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
nlog.Log(LogLevel.Debug, "Debug");
nlog.Log(LogLevel.Info, "Info");
try
{
throw new Exception("異常");
}
catch (Exception ex)
{
nlog.Log(LogLevel.Error, ex, "異常的附加資訊");
}
return new string[] { "value1", "value2" };
}