做網站英文編輯有前途嗎成人大專
Nlog是什么?
NLog是一個為.NET平臺設計的靈活且免費的日志記錄庫。它適用于包括.NET Framework、.NET Core和.NET Standard在內的多種.NET環(huán)境。
Nlog有什么好處或者特點?
-
配置靈活:NLog允許開發(fā)者通過配置文件(通常是NLog.config)來設定日志記錄的行為,如日志級別、輸出目標等,而無需修改代碼。配置更改可即時生效,無需重啟應用。
-
多目標記錄:支持將日志信息輸出到多個目的地(或稱為“目標”),如控制臺、文件系統(tǒng)、數據庫、電子郵件、網絡Socket等,這為日志管理和分析提供了便利。
-
日志級別管理:定義了多個日志級別,包括Trace、Debug、Info、Warn、Error和Fatal,使得開發(fā)者可以根據情況記錄不同重要性的信息,并且可以設定記錄的最低和最高級別。
-
性能優(yōu)化:設計注重性能,確保在高負載環(huán)境下也能高效地記錄日志。
-
結構化日志記錄:支持日志消息的結構化輸出,便于日志數據的自動化處理和分析。
-
模板變量與布局渲染器:提供了豐富的模板變量(如${date}, ${level}, ${message}等)和布局渲染器,使得日志信息的格式化更加靈活和強大。
-
即時配置變更:可以在應用程序運行時動態(tài)改變日志配置,無需重新部署。
-
擴展性:用戶可以自定義日志目標、布局渲染器等,以滿足特定需求。
-
開源與社區(qū)支持:作為開源項目,NLog擁有活躍的社區(qū)支持,持續(xù)更新和改進,同時也鼓勵用戶貢獻代碼和插件。
快速上手
準備工作
因為接上篇文章,我的項目里已經使用了log4net,所以我們使用Nlog的話暫時先注釋掉之前的log4net,如果你的項目是干凈的,那就直接看下個步驟哇~~
安裝依賴 NLog.Web.AspNetCore
準備NLog配置文件
新建xiaojinWebApplication\configFile\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"xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"autoReload="true"throwExceptions="false"internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"><!-- optional, add some variableshttps://github.com/nlog/NLog/wiki/Configuration-file#variables--><variable name="myvar" value="myvalue"/><!--See https://github.com/nlog/nlog/wiki/Configuration-filefor information on customizing logging rules and outputs.--><targets><!--add your targets hereSee https://github.com/nlog/NLog/wiki/Targets for possible targets.See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.--><!-- <target name="AllDatabase" xsi:type="Database"dbProvider="System.Data.SqlClient.SqlConnection, System.Data.SqlClient"connectionString="Data Source=PC-202206030027;Initial Catalog=LogManager;Persist Security Info=True;User ID=sa;Password=sa123"commandText="insert into dbo.NLog (Application, Logged, Level, Message,Logger, CallSite, Exception) values (@Application, @Logged, @Level, @Message,@Logger, @Callsite, @Exception);"><parameter name="@application" layout="AspNetCoreNlog" /><parameter name="@logged" layout="${date}" /><parameter name="@level" layout="${level}" /><parameter name="@message" layout="${message}" /><parameter name="@logger" layout="${logger}" /><parameter name="@callSite" layout="${callsite:filename=true}" /><parameter name="@exception" layout="${exception:tostring}" /></target> --><target xsi:type="File" name="allfile" fileName="NLog\nlog-all-${shortdate}.log"layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /><!--同樣是將文件寫入日志中,寫入的內容有所差別,差別在layout屬性中體現。寫入日志的數量有差別,差別在路由邏輯中體現--><!-- <target xsi:type="File" name="ownFile-web" fileName="NLog\nlog-my-${shortdate}.log"layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /><target xsi:type="Null" name="blackhole" /> --><!--Write events to a file with the date in the filename.<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"layout="${longdate} ${uppercase:${level}} ${message}" />--></targets><rules><logger name="*" minlevel="Trace" writeTo="AllDatabase" /><!-- add your logging rules here --><!--路由順序會對日志打印產生影響。路由匹配邏輯為順序匹配。--><!--All logs, including from Microsoft--><logger name="*" minlevel="Trace" writeTo="allfile" /><!--Skip Microsoft logs and so log only own logs--><!--以Microsoft打頭的日志將進入此路由,由于此路由沒有writeTo屬性,所有會被忽略--><!--且此路由設置了final,所以當此路由被匹配到時。不會再匹配此路由下面的路由。未匹配到此路由時才會繼續(xù)匹配下一個路由--><logger name="Microsoft.*" minlevel="Trace" final="true" /><!--上方已經過濾了所有Microsoft.*的日志,所以此處的日志只會打印除Microsoft.*外的日志--><logger name="*" minlevel="Trace" writeTo="ownFile-web" /><!--Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"<logger name="*" minlevel="Debug" writeTo="f" />--></rules>
</nlog>
配置項詳解
- 標簽定義了一個NLog的配置文件。
- xmlns屬性定義了NLog的命名空間,xsi:schemaLocation屬性指定了NLog的XSD文件的位置。
- autoReload屬性設置為true表示配置文件發(fā)生變化時會自動重新加載。
- throwExceptions屬性設置為false表示不會拋出異常。
- internalLogLevel屬性設置為Off表示關閉內部日志記錄。
- internalLogFile屬性指定了內部日志文件的路徑。
- 標簽用于定義變量,這里的myvar變量被定義為myvalue。
- 標簽定義了日志的目標,例如數據庫、文件等。
- 標簽定義了一個名為AllDatabase的日志目標,它是一個數據庫目標,使用SQL Server數據庫。
- dbProvider屬性指定了數據庫提供程序。
- connectionString屬性指定了數據庫連接字符串。
- commandText屬性指定了SQL命令文本。
- 標簽定義了SQL命令中的參數。
- 標簽還定義了其他日志目標,例如文件目標。
- 標簽定義了日志記錄的規(guī)則。
- 標簽定義了一個日志記錄器,它指定了日志記錄的級別和要寫入的目標。
- name屬性指定了日志記錄器的名稱。
- minlevel屬性指定了日志記錄的最小級別。
- writeTo屬性指定了要寫入的日志目標。
- final屬性設置為true表示此規(guī)則是最終規(guī)則,不會再匹配后續(xù)規(guī)則。 通過這個配置文件,可以將日志記錄到數據庫和文件中,并且可以自定義日志記錄的級別和路由邏輯。
注冊日志組件
xiaojinWebApplication\Program.cs
// Nlog---startbuilder.Logging.AddNLog("configFile/NLog.Config");// Nlog---end
添加日志記錄代碼
看過我log4net文章的小伙伴,這個步驟可以省略哦~~,我們在代碼里添加下面的日志調用邏輯,例如:xiaojinWebApplication\Controllers\CommonInfoController.cs
private readonly ILogger<CommonInfoController> _logger; // 方案一private readonly ILoggerFactory _ILoggerFactory; // 方案二public CommonInfoController(ILogger<CommonInfoController> logger, ILoggerFactory iLoggerFactory){_logger = logger;_logger.LogInformation("方案一 LogInformation; this is CommonInfoController 構造函數~");_logger.LogError("方案一LogError: this is CommonInfoController 構造函數~");_logger.LogWarning("方案一LogWarning: this is CommonInfoController 構造函數~");_logger.LogDebug("方案一LogDebug:this is CommonInfoController 構造函數~");_ILoggerFactory = iLoggerFactory; // 方案二ILogger<CommonInfoController> _loger2 = _ILoggerFactory.CreateLogger<CommonInfoController>();_loger2.LogInformation("方案二LogInformation; this is CommonInfoController 構造函數~");_loger2.LogError("方案二LogError: this is CommonInfoController 構造函數~");_loger2.LogWarning("方案二LogWarning: this is CommonInfoController 構造函數~");_loger2.LogDebug("方案二LogDebug:this is CommonInfoController 構造函數~");}/// <summary>/// 測試接口01/// </summary>/// <returns></returns>[HttpGet(Name = "getCommonInfo")]public CommonInfo getCommonInfo(){_logger.LogInformation("測試接口01~");_logger.LogError("測試接口01~");_logger.LogWarning("測試接口01~");_logger.LogDebug("測試接口01~");return new CommonInfo{Date = DateOnly.FromDateTime(DateTime.Now),Text = "getCommonInfo"};}
運行代碼
查看日志
打開xiaojinWebApplication\bin\Debug\net8.0\NLog\nlog-all-2024-05-07.log
大功告成
好了,等我數據庫搭建好以后,下篇文章會記錄如何使用數據庫記錄日志,大家也可以直接把代碼注釋打開,記得修改一下數據庫的默認配置哦~
學習參考:
- 微軟MVP-Eleven
結語
- 今天就寫到這里啦~
- 小伙伴們,( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ我們明天再見啦~~
- 大家要天天開心哦
歡迎大家指出文章需要改正之處~
學無止境,合作共贏