NetCore3.1 日志组件 Nlog的使用

1.添加Nuget程序包

 NLog 

NLog.Web.AspNetCore

NetCore3.1 日志组件 Nlog的使用

2.创建名称为: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">
    <!-- 启用.net core的核心布局渲染器 -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore" />
    </extensions>
    <!-- 写入日志的目标配置 -->
    <targets>
        <!-- 调试  -->
        <target xsi:type="File" name="debug" fileName="logs/debug-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
        <!-- 警告  -->
        <target xsi:type="File" name="warn" fileName="logs/warn-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
        <!-- 错误  -->
        <target xsi:type="File" name="error" fileName="logs/error-${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>
        <!-- 调试  -->
        <logger name="*" minlevel="Trace" maxlevel="Debug" writeTo="debug" />
        <!--跳过不重要的微软日志-->
        <logger name="Microsoft.*" maxlevel="Info" final="true" />
        <!-- 警告  -->
        <logger name="*" minlevel="Info" maxlevel="Warn" writeTo="warn" />
        <!-- 错误  -->
        <logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="error" />
    </rules>
</nlog>

3.Program.cs 添加Nlog

public class Program
    {
        public static void Main(string[] args)
        {
            //这里添加Nlog
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
            try
            {
                //测试Nlog日志输出
                logger.Debug("init main");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseNLog();//添加你的日志组件
    }

4.通过构造方法注入实现写日志功能

using FranchiseeInterface.Franchisee;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FranchiseeApi.Helper.Middlewares
{
    public class ExceptionMiddlewares
    {
        private readonly RequestDelegate next;
        private IHostingEnvironment environment;
        //Nlog构造方法注入
        private readonly ILogger<ExceptionMiddlewares> _logger;
        public ExceptionMiddlewares(RequestDelegate next, IHostingEnvironment environment, ILogger<ExceptionMiddlewares> logger)
        {
            _logger = logger;
            this.next = next;
            this.environment = environment;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next.Invoke(context);
                var features = context.Features;
            }
            catch (Exception e)
            {
                await HandleException(context, e);
            }
        }

        private async Task HandleException(HttpContext context, Exception e)
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/json;charset=utf-8;";
            string error = "";

            if (environment.IsDevelopment())
            {
                var json = new { message = e.Message };
                //// log.Error(json);
                //_logger.LogDebug("这里是homeController构造方法");
                //_logger.Log(LogLevel.Information,"测试");
                _logger.LogError(JsonConvert.SerializeObject(json));
                error = JsonConvert.SerializeObject(json);
            }
            else
                error = "抱歉,出错了";

            await context.Response.WriteAsync(error);
        }
    }
}

至此,就结束了。

NetCore3.1 日志组件 Nlog的使用

上一篇:数据结构(一) 前言


下一篇:谷歌浏览器之http请求分析