[.Net Core] 在 Mvc 中簡單使用日誌組件

在 Mvc 中簡單使用日誌組件

  基於 .Net Core 2.0,本文只是走馬觀花,並不是深刻淺出。html

 

目錄

  • 使用內置的日誌組件
  • 簡單過渡到第三方組件 - NLog

 

使用內置的日誌

  下面使用控制器 HomeController.cs 進行演示。git

  須要 using Microsoft.Extensions.Logging;github

 

  方案一:web

    public class HomeController : Controller
    {
        private readonly ILogger _logger ;

        public HomeController(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger(typeof(HomeController));
        }
    }

 

  方案二:json

    public class HomeController : Controller
    {
        private readonly ILogger _logger ;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
    }

 

  方案三:mvc

    public class HomeController : Controller
    {
        private readonly ILogger _logger ;

        public HomeController(ILogger logger)
        {
            _logger = logger;
        }
    }

 

  三種都是經過注入的方式獲取日誌記錄器對象,在過去,咱們會本身獨立封裝相似這些 Debug、Info 和 Error 等不一樣日誌等級的方法,如今咱們看看內置的方法是如何使用的?app

 

  在 HomeController 內添加 Index() 方法進行測試。post

        public IActionResult Index()
        {
            _logger.LogDebug($"測試:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
            _logger.LogError($"測試:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
            _logger.LogInformation($"測試:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");

            return Json(Guid.NewGuid());
        }

 

  在輸出結果中咱們能夠看到,不一樣日誌的等級在控制檯中會以不一樣的顏色進行標註。測試

 

  每種級別的 Log 都有多個方法重載,如 LogInformation() ,示例演示的代碼中使用的是比較簡單一種,也就是最後一種。ui

        //
        // 摘要:
        //     Formats and writes an informational log message.
        //
        // 參數:
        //   logger:
        //     The Microsoft.Extensions.Logging.ILogger to write to.
        //
        //   eventId:
        //     The event id associated with the log.
        //
        //   message:
        //     Format string of the log message.
        //
        //   args:
        //     An object array that contains zero or more objects to format.
        public static void LogInformation(this ILogger logger, EventId eventId, string message, params object[] args);
        //
        // 摘要:
        //     Formats and writes an informational log message.
        //
        // 參數:
        //   logger:
        //     The Microsoft.Extensions.Logging.ILogger to write to.
        //
        //   exception:
        //     The exception to log.
        //
        //   message:
        //     Format string of the log message.
        //
        //   args:
        //     An object array that contains zero or more objects to format.
        public static void LogInformation(this ILogger logger, Exception exception, string message, params object[] args);
        //
        // 摘要:
        //     Formats and writes an informational log message.
        //
        // 參數:
        //   logger:
        //     The Microsoft.Extensions.Logging.ILogger to write to.
        //
        //   message:
        //     Format string of the log message.
        //
        //   args:
        //     An object array that contains zero or more objects to format.
        public static void LogInformation(this ILogger logger, string message, params object[] args);

  

  其它細節以及詳情,或者但願使用其它日誌組件可參考官方文檔:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x

 

簡單過渡到第三方組件 - NLog

  Nuget 安裝 NLog.Web.AspNetCore(目前 Nuget 最新爲 4.4.1,可是官方的教程倒是 4.5 的,小編使用 4.4.1 進行演示)。如需 4.5+ 可參考官方:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

 

  下面演示如何將內置的組件簡單的移植到 NLog 中。

  先在根目錄建立配置文件 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.txt">


  <!-- the targets to write to -->
  <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}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <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" />
  </rules>
</nlog>

 

  修改 Startup.cs 類中的 Configure() 方法,其它地方都不須要作出任何修改。

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();    //添加NLog  
            env.ConfigureNLog("nlog.config");    //讀取Nlog配置文件  

            //...        
        }

 

  啓動程序,你會發現:

 

 

 

【原文】http://www.cnblogs.com/liqingwen/p/8613538.html 


相關的文章:

  《[.Net Core] 簡單讀取 json 配置文件

  《[.Net Core] 簡單使用 Mvc 內置的 Ioc

  《[.Net Core] 簡單使用 Mvc 內置的 Ioc(續)

  《[.Net Core] 在 Mvc 中簡單使用日誌組件

相關文章
相關標籤/搜索