1. 程式人生 > >循序漸進學.Net Core Web Api開發系列【10】:使用日誌

循序漸進學.Net Core Web Api開發系列【10】:使用日誌

系列目錄

一、本篇概述

本篇介紹日誌的使用,包括系統預設的控制檯日誌和第三方NLog日誌管理。

二、使用系統控制檯日誌

1、使用內建日誌

    [Produces("application/json")]
    [Route("api/Article")]
    public class ArticleController : Controller
    {      private readonly ILogger _logger;
        public ArticleController(SalesContext context, ILogger<ArticleController> logger)
        {          
_logger = logger; } [HttpGet("logger")] public void TestLogger() { _logger.LogCritical("LogCritical"); _logger.LogError("LogError"); _logger.LogWarning("LogWarning"); _logger.LogInformation(
"LogInformation"); _logger.LogDebug("LogDebug"); return; } }

預設只能看到前三條記錄:

主要原因是日誌的最低級別預設為Warring,如果要顯示其他級別日誌,需要修改application.json檔案。 

{  
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Error"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Information
" } } } }

日誌級別優先順序如下順序:

Critical > Error > Warning > Information > Debug

調整日誌級別為Information 或Debug以後會顯示太多無關的日誌資訊,可以配置預設級別為Warring,而自己專案名稱空間的日誌級別為Debug。

"Console": {
      "LogLevel": {
        "Default": "Warning",
        "SaleService.Controllers": "DEBUG"
      }
    }

2、幾點說明

1)目前日誌已經可以正常工作了,把專案釋出到Linux環境下,通過配置Supervisor可以把控制檯的內容輸出到檔案系統,建議在除錯環境下采用Debug日誌級別,而在生成環境採用Error日誌級別。配置Supervisor的內容可以參考:循序漸進學.Net Core Web Api開發系列【7】:專案釋出

 2)如果稍微瞭解依賴注入(DI)的知識,就可以理解我們在Controoler中使用ILogger是採用標準的建構函式注入的方式,但是問題是使用者並沒有註冊該服務,其實是系統在CreateDefaultBuilder時幫我們註冊了日誌服務。可以看幾段原始碼的片段:

CreateDefaultBuilder:
using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore
{   
    public static class WebHost
    { 
        public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            return WebHostBuilderIISExtensions.UseIISIntegration(HostingAbstractionsWebHostBuilderExtensions.UseContentRoot(WebHostBuilderKestrelExtensions.UseKestrel(new WebHostBuilder()), Directory.GetCurrentDirectory()).ConfigureAppConfiguration(delegate(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
            {
                IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
                JsonConfigurationExtensions.AddJsonFile(JsonConfigurationExtensions.AddJsonFile(config, "appsettings.json", true, true), string.Format("appsettings.{0}.json", hostingEnvironment.EnvironmentName), true, true);
                if (HostingEnvironmentExtensions.IsDevelopment(hostingEnvironment))
                {
                    Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                    if (assembly != null)
                    {
                        UserSecretsConfigurationExtensions.AddUserSecrets(config, assembly, true);
                    }
                }
                EnvironmentVariablesExtensions.AddEnvironmentVariables(config);
                if (args != null)
                {
                    CommandLineConfigurationExtensions.AddCommandLine(config, args);
                }
            }).ConfigureLogging(delegate(WebHostBuilderContext hostingContext, ILoggingBuilder logging)
            {
                LoggingBuilderExtensions.AddConfiguration(logging, hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            })).UseDefaultServiceProvider(delegate(WebHostBuilderContext context, ServiceProviderOptions options)
            {
                options.ValidateScopes = HostingEnvironmentExtensions.IsDevelopment(context.HostingEnvironment);
            });
        }
    }
}
AddConsole:
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Console;

namespace Microsoft.Extensions.Logging
{   
    public static class ConsoleLoggerExtensions
    {       
        public static ILoggingBuilder AddConsole(this ILoggingBuilder builder)
        {
            builder.Services.AddSingleton<ILoggerProvider, ConsoleLoggerProvider>();
            return builder;
        }       
    }
}

三、使用NLog

1、通過NuGet獲取包:NLog.Web.AspNetCore

2、修改Startup類的Configure方法:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }       

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); loggerFactory.ConfigureNLog("nlog.config"); //如果採用預設配置檔案nlog.config,該語句可以省略 } }

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">
  <targets>
    <target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}_all.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
    <target xsi:type="File" name="debugfile" fileName="${basedir}/logs/${shortdate}_debug.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
    <target xsi:type="File" name="errfile" fileName="${basedir}/logs/${shortdate}_error.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
  </targets>
  <rules>
    <logger name="*" level="Debug" writeTo="debugfile" />
    <logger name="*" level="Error" writeTo="errfile" />    
    <logger name="*" minlevel="Trace" writeTo="logfile" />
  </rules>
</nlog>

專案釋出時修改配置檔案,只保留errfile即可。

以上就是全部程式碼,Controller中的程式碼無需修改。

3、兩個注意點

1)目前我們已經採用NLog來進行日誌的記錄,此時系統預設的日誌仍然是正常工作的,專案釋出時建議把系統預設的日誌級別改成Error,nlog的輸出日誌只保留errfile,以免造成伺服器磁碟空間浪費。

2)專案釋出時nlog.config檔案可能不會發布到目標目錄,需要修改該檔案的檔案屬性: