Asp.Net Core基礎NLog記錄日志


 

Asp.Net Core自帶內建日志,同時也允許開發人員輕松切換到其他日志框架。下面將在實戰項目中使用NLog記錄日志。

1.首先創建Asp.Net Core Web項目

2.在項目中添加NLog相應包

  

Install-Package NLog.Web.AspNetCore -Version 4.8.0

3.在項目中添加NLog配置文件

 

Install-Package NLog.Config

NLog.config添加至項目中后,在VS中右擊文件,查看屬性,並將文件屬性設置為始終復制或者更新時復制

4.編輯NLog.config文件

雙擊文件,進入編輯,根據需要修改內容。

配置文件主要包括兩個部分:輸出目標target路由規則rule。

4.1輸出目標target

每個target代表一個輸出目標,它主要包含兩個屬性:name和type。name是輸出模板的名稱,在后面的路由規則中使用,type則是輸出類型,常見的有

  • Console        輸出到控制台
  • Debugger     輸出到
  • File        輸出到文件
  • Mail        輸出為郵件發送
  • Network        輸出到網絡地址
  • Database        輸出到數據庫

當選擇某一種類型的時候,還需要配置相應的參數。如輸出類型是File時,我們要配置日志路徑filename,這里是可以使用一些變量的(花括號里面的部分),舉例:

    fileName="${basedir}/Logs/Error/${shortdate}/error.txt"

輸出的日志格式為 /Log/2014-10-01/err.txt    每天生成一個文件夾,非常方便。

輸出格式的控制:

有的時候,我們需要對時間、異常等這些對象的輸出格式進行控制。它們可以通過修改layout參數來實現。這一部分是相對比較復雜的,具體配置參數請到官網查看。

4.2路由規則rule

路由規則主要用於將日志和輸出目標匹配起來,它一般有如下幾個屬性

  • name - 記錄者的名字 (允許使用通配符*)
  • minlevel - 匹配日志范圍的最低級別
  • maxlevel - 匹配日志范圍的最高級別
  • level - 匹配的單一日志級別
  • levels - 匹配的一系列日志級別,由逗號分隔。
  • writeTo - 規則匹配時日志應該被寫入的一系列目標,由逗號分隔。

看上去有好幾個屬性,實際上用起來還是比較簡單的,比如:

    <logger name="*" writeTo="console" />    將所有的日志輸出到控制台中
    <logger name="*" minlevel="Debug" writeTo="debugger" />            將Debug級別以上的日志輸出到Debugger中
    <logger name="*" minlevel="Error" writeTo="error_file" />        將Error級別以上的日志輸出到文件中

另外,NLOG支持配置多個路由規則,可以非常方便我們的輸出。

具體詳情請看官網參數說明:https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-locations

下面是我的配置文件:

<?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 variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <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}" />

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    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>
    <!--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" />


    <!--
    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>

5.在startup.cs中注入日志

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
     env.ConfigureNLog("NLog.config");
     Configuration = configuration;
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
      //...
            
      //add NLog to ASP.NET Core
      loggerFactory.AddNLog();
            
      //...

}

運行項目后,產生日志記錄

 6.全局異常處理

添加過濾器;並在Startup.cs文件的ConfigureServices方法中添加過濾器

public class GlobalExceptionFilter: IExceptionFilter
    {
       public static Logger logger = LogManager.GetCurrentClassLogger();

        public void OnException(ExceptionContext filterContext)
        {
            logger.Error(filterContext.Exception);
            var result = new BaseResult()
            {
                ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode,//系統異常代碼
                ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg,//系統異常信息
            };
            filterContext.Result = new ObjectResult(result);
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.ExceptionHandled = true;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM