zoukankan      html  css  js  c++  java
  • NetCore3.1 日志组件 Nlog的使用

    1.添加Nuget程序包

     NLog 

    NLog.Web.AspNetCore

    NetCore3.1 日志组件 Nlog的使用-LMLPHP

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

    至此,就结束了。

  • 相关阅读:
    大道至简第二章读后感
    读大道至第一章简有感
    二次封装Response类
    视图与序列化传参
    Codeforces Round #523 (Div. 2) F. Katya and Segments Sets (交互题+思维)
    Codeforces Round #510 (Div. 2) D. Petya and Array(离散化+反向树状数组)
    Codeforces 1060E(思维+贡献法)
    Codeforces Round #520 (Div. 2) E. Company(dfs序判断v是否在u的子树里+lca+线段树)
    Codeforces Round #513 by Barcelona Bootcamp C. Maximum Subrectangle(双指针+思维)
    Educational Codeforces Round 51 F. The Shortest Statement(lca+最短路)
  • 原文地址:https://www.cnblogs.com/zxtceq/p/14149146.html
Copyright © 2011-2022 走看看