asp.net core NLog 配置


NuGet 添加引用NLog.Config 和 NLog.Web.AspNetCore
添加NLog.Config引用時會自動在項目根目錄生成一個NLog.config文件,把文件屬性設置成總是復制

 

日志級別:Trace -> Debug-> Information -> Warning -> Error-> Critical


修改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 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> <!-- 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}" /> --> <!--Error保存至文件--> <target name="error_file" xsi:type="File" maxArchiveFiles="30" encoding="utf-8" fileName="${basedir}/Logs/${date:yyyyMMdd}_Error.log" archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_Error.{#}.log" archiveDateFormat="yyyyMMdd" archiveAboveSize="104857600" archiveNumbering="Sequence" layout="${date:yyyy-MM-dd HH\:mm\:ss} ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace}" /> <!--Trace保存至文件--> <target name="trace_file" xsi:type="File" maxArchiveFiles="30" encoding="utf-8" fileName="${basedir}/Logs/${date:yyyyMMdd}_Trace.log" archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_Trace.{#}.log" archiveDateFormat="yyyyMMdd" archiveAboveSize="104857600" archiveNumbering="Sequence" layout="${date:yyyy-MM-dd HH\:mm\:ss} ${uppercase:${level}}: ${message}" /> </targets> <rules> <!-- add your logging rules here --> <logger name="*" minlevel="Trace" maxlevel="Warn" writeTo="trace_file" /> <!--<logger name="*" minlevel="Debug" writeTo="debugger" />--> <logger name="*" minlevel="Error" writeTo="error_file" /> <!-- 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>

在Program.cs文件中添加如下代碼:

            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
            }).UseNLog()

添加后如下:

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureLogging(logging => { logging.ClearProviders(); }).UseNLog();

注入和調用如下:

        private readonly ILogger<BusinessController> _logger; public BusinessController(ILogger<BusinessController> logger) { _logger = logger; } [HttpGet] public string Test() { var json = DateTime.Now.ToString(); _logger.LogInformation(json); _logger.LogError(json); _logger.LogDebug(json); _logger.LogCritical(json); _logger.LogTrace(json); _logger.LogWarning(json); return json; }

輸出文件位置\bin\Debug\netcoreapp3.1,目錄中會自建一個文件夾Logs

\bin\Debug\netcoreapp3.1\Logs

 

全局異常,添加過濾器;並在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;
        }
    }

 

  xsi:type:將文件類型設置為File,將日志保存到文件中。

  fileName:將日志文件保存到"${logDir}/InfoLogs/log.txt"。

  archiveFileName:為了防止日志文件保存的太大,我們將日志文件拆分保存。通過archiveFileName參數設置保存格式,具體格式可以到這里查看。

  createDirs:若設置的日志文件夾不存在,則自動創建文件夾。

  keepFileOpen:為了提高文件寫入性能,避免每次寫入文件都開關文件,將keepFileOpen設置為true,我們通過openFileCacheTimeout參數定時關閉文件。

  autoFlush:為了提高日志寫入性能,不必每次寫入日志都直接寫入到硬盤上,將autoFlush設置為false,我們通過openFileFlushTimeout參數定時寫入文件。

  openFileCacheTimeout:將keepFileOpen參數設置為false,則設置定時關閉日志。防止日志一直開着占用着。

  openFileFlushTimeout:將autoFlush參數設置為false,則設置定時將日志從緩存寫入到硬盤時間。

  archiveAboveSize:為了防止一個文件日志太大,我們需要根據指定大小將日志拆文件保存。archiveAboveSize參數的單位是字節。通過設置為10240=10KB,每個日志大小達到10KB就會自動拆分文件,拆分后的文件名規則通過archiveFileName設置,拆分文件名的規則通過archiveNumbering設置,具體規則可以查看這里。

  concurrentWrites:支持多個並發一起寫文件,提高文件寫入性能。

  encoding: Nlog默認保存的編碼格式為Encoding.Default,中文保存到日志中會出現亂碼,將其設置為utf-8,就可以正常保存了。

  

參考

  Asp.Net Core基礎NLog記錄日志

  asp.net core 自定義認證方式--請求頭認證

  示例項目

  Net Core平台靈活簡單的日志記錄框架NLog+Mysql組合初體驗

  ASP.NET Core 教程:NLog 的使用


免責聲明!

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



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