點選上方 工具 (Tools) > NuGet 套件管理員 (NuGet Package Manager) > 管理方案 NuGet 套件(Manage NuGet Packages for Solution)
瀏覽頁簽內的搜尋框輸入 nlog,即可以找到相關套件。我們這次要安裝的套件有三個,分別是: NLog、NLog.Config 與 NLog.Web.AspNetCore
先開啟專案中的 Program.cs,如下方圖片加入 .UseNLog();
Main 內修改如下圖
完整程式碼如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); | |
try | |
{ | |
logger.Debug("init main"); | |
CreateHostBuilder(args).Build().Run(); | |
} | |
catch (Exception ex) | |
{ | |
logger.Error(ex, "Stopped program because of exception"); | |
throw; | |
} | |
finally | |
{ | |
NLog.LogManager.Shutdown(); | |
} | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.UseStartup<Startup>(); | |
}).UseNLog(); | |
} |
找到並右鍵點選 NLog.config,選擇屬性 (Properties) ,將 複製到輸出目錄 (Copy to Output Directory) 選擇 永遠複製 (Copy always)
接下來打開 NLog.config,你能看到許多註解,這些都是基本的設定範例。
首先我們先看一下 targets (目標) 設定:
xsi:type: 寫入log 格式,File 表示將log 寫入檔案
fileName: 為寫入檔案的位置, ${basedir} 為專案資料夾
layout: 為寫出的格式,這邊格視為時間、大寫 Log level與 log 內容 (meassage)
接下來我們看一下 rules (規則)設定
logger name: 可以設定寫出那些 logger,* 表示全部都寫
minlevel: 表示寫出log的層級
writeTo: 表示寫出位置,f 表示檔案 (對應上面 target name=f)
我們將 NLog.config 內 targets 與 rules 註解拿掉
使用 nlog 有兩種方式:直接使用 與 注入使用,直接使用的方式在上面有提到 (加入到 Program.cs 內容) 只需要 var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 取得目前 Logger,再透過 logger.Debug("init main"); 寫入 log 即可
另一種方式是注入方式,無論在 controllers 或 services 於建構子注入後即可使用:
完成設定後啟動專案,你能在專案目錄下 (\bin\Debug\netcoreapp3.1\logs) 下找到 log
0 留言