1. 程式人生 > >ASP.NET Core學習之三 NLog日誌

ASP.NET Core學習之三 NLog日誌

width itl .com 添加引用 manage skip mono cas ans

上一篇簡單介紹了日誌的使用方法,也僅僅是用來做下學習,更何況只能在console輸出。

NLog已是日誌庫的一員大佬,使用也簡單方便,本文介紹的環境是居於.NET CORE 2.0 ,目前的版本也只有beta版。

一、安裝和配置

1.安裝

命令如下

PM> Install-Package NLog.Web.AspNetCore -Version 4.5.0-beta04

2.創建配置文件

在web項目根目錄下,創建配置文件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}" />

    <!-- 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}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <!-- write to the void aka just remove -->
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

3.初始化

更新program.cs,添加引用

using NLog.Web;

修改代碼

public static void Main(string[] args)
{
    // NLog: setup the logger first to catch all errors
    var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        BuildWebHost(args).Run();
    }
    catch (Exception e)
    {
        //NLog: catch setup errors
        logger.Error(e, "Stopped program because of exception");
        throw;
    }
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseNLog() // NLog: setup NLog for Dependency injection
        .Build();

二、使用

配置好了之後,將ILogger註入到控制器就可以寫日誌了。

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

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

    public IActionResult Index()
    {
        _logger.LogInformation("Index page says hello");
        return View();
    }
}

三、日誌輸出

訪問剛才的index就可以在日誌目錄下看到2個生成的文件了。

nlog-all-2017-11-18.log

2017-11-18 23:09:02.2839||DEBUG|Tkx.Web.Program|init main 
2017-11-18 23:09:02.6079||INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using ‘C:\Users\Administrator\AppData\Local\ASP.NET\DataProtection-Keys‘ as key repository and Windows DPAPI to encrypt keys at rest. 
2017-11-18 23:09:03.0070||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 POST http://localhost:59491/account/login application/x-www-form-urlencoded 26 
2017-11-18 23:09:03.0320||INFO|Microsoft.AspNetCore.Cors.Infrastructure.CorsService|Policy execution successful. 
2017-11-18 23:09:03.1720||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method Tkx.Web.Controllers.AccountController.Login (Tkx.Web) with arguments (Tkx.WebApi.Models.User.UserLogin) - ModelState is Valid 
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|================ 
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|LOGIN IS START:admin 123 
2017-11-18 23:09:03.1950||INFO|Tkx.Web.Controllers.AccountController|================ 
2017-11-18 23:09:03.1950||INFO|Tkx.IBusiness.Implement.UserService|UserService param:admin 123 
2017-11-18 23:09:03.3440||INFO|Tkx.IBusiness.Implement.UserService|UserService count:1 
2017-11-18 23:09:03.3500||INFO|Tkx.IBusiness.Implement.UserService|UserService: 
2017-11-18 23:09:03.3500||INFO|Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor|Executing JsonResult, writing value Tkx.Web.ResponseMessage. 
2017-11-18 23:09:03.5290||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action Tkx.Web.Controllers.AccountController.Login (Tkx.Web) in 398.631ms 
2017-11-18 23:09:03.5440||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 543.2871ms 200 application/json; charset=utf-8

nlog-own-2017-11-18.log

2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|================ |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|LOGIN IS START:admin 123 |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.1950||INFO|Tkx.Web.Controllers.AccountController|================ |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.1950||INFO|Tkx.IBusiness.Implement.UserService|UserService param:admin 123 |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.3440||INFO|Tkx.IBusiness.Implement.UserService|UserService count:1 |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.3500||INFO|Tkx.IBusiness.Implement.UserService|UserService: |url: http://localhost/account/login|action: login

在業務層使用方法一樣簡單,只要在業務層引入該庫就可以。 如日誌所顯示的UserService就是我的業務層。 寫到最後,說一句,其實就是翻譯了官網的文檔而已

相關文檔

項目地址:https://github.com/NLog/NLog.Web nlog使用方法
https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2
配置文件的詳細使用說明
https://github.com/NLog/NLog/wiki/Configuration-file

ASP.NET Core學習之三 NLog日誌