按部就班學.Net Core Web Api開發系列【10】:使用日誌

系列目錄html

按部就班學.Net Core Web Api開發系列目錄git

 本系列涉及到的源碼下載地址:https://github.com/seabluescn/Blog_WebApigithub

 

1、本篇概述json

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

 

2、使用系統控制檯日誌服務器

一、使用內置日誌app

    [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;
        }
    }

默認只能看到前三條記錄:ide

主要緣由是日誌的最低級別默認爲Warring,若是要顯示其餘級別日誌,須要修改application.json文件。 函數

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

日誌級別優先級以下順序:ui

Critical > Error > Warning > Information > Debug

調整日誌級別爲Information 或Debug之後會顯示太多無關的日誌信息,能夠配置默認級別爲Warring,而本身項目命名空間的日誌級別爲Debug。

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

 

二、幾點說明

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;
        }       
    }
}

 

3、使用NLog

一、經過NuGet獲取包:NLog.Web.AspNetCore

二、修改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中的代碼無需修改。

 

三、兩個注意點

1)目前咱們已經採用NLog來進行日誌的記錄,此時系統默認的日誌仍然是正常工做的,項目發佈時建議把系統默認的日誌級別改爲Error,nlog的輸出日誌只保留errfile,以避免形成服務器磁盤空間浪費。

2)項目發佈時nlog.config文件可能不會發布到目標目錄,須要修改該文件的文件屬性:

相關文章
相關標籤/搜索