在webapi專案下使用NLog套件
同步更新於個人部落格
NLog範例
選擇ASP.NET Core Web API專案範本,並執行下一步
命名你的專案名稱,並選擇專案要存放的位置。
直接進行下一步
在根目錄新增nlog.config檔案
在nlog.config寫入官方範例
<?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-AspNetCore.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- File Target for all log messages with basic details -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />
<!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
<target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Output hosting lifetime messages to console target for faster startup detection -->
<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
<!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="System.Net.Http.*" maxlevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
只擷取部分畫面
在Program寫入官方範例
using NLog;
using NLog.Web;
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");
try {
var builder = WebApplication.CreateBuilder(args);
//將NLog註冊到此專案內
builder.Logging.ClearProviders();
//設定log紀錄的最小等級
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
builder.Host.UseNLog();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
} catch (Exception ex) {
// 捕獲設定錯誤的錯誤紀錄
logger.Error(ex, "Stopped program because of exception");
throw;
} finally {
//須確定在關閉時,把nlog關閉
LogManager.Shutdown();
}
只擷取部分畫面
將原先存在的default移除
{
"Logging": {
"LogLevel": {
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
在預設的controller裡面寫入Log,如下圖紅框處
//寫在建構子內
_logger.LogDebug(1, "NLog injected into HomeController");
//寫在action內
_logger.LogInformation("這是範例程式預設的controller!!");
點try it out後點execute,確定執行完成查看console檔案(執行專案會啟動一個terminal)
步驟六有在設定檔內設定log存放路徑,c:\temp\internal-nlog-AspNetCore.txt
完成範例說明後建議使用Serilog,因為相對來說單純一點,對於設定上來說nlog真的比較複雜。