Asp.net Core 中间件获取调用接口的信息并记录到nlog日志文件中

庾奇思
2023-12-01

CustomExceptionMiddleware类代码 如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Logging;
using Nestle.Portal.Utility.Models;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace DuratiMiddlewareonCollectService.
{
    /// <summary>
    /// 自定义异常中间件
    /// </summary>
    public class CustomExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CustomExceptionMiddleware> _logger;
        public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                HttpRequest request = httpContext.Request;
                Dictionary<string, object> errorData = new Dictionary<string, object>();
                errorData.Add("URL", request.Path.ToString());
                errorData.Add("Method", request.Method);
                if (request.Method.ToLower().Equals("post"))
                {
                    request.EnableRewind();
                    Stream stream = request.Body;
                    byte[] buffer = new byte[request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    errorData.Add("Body", Encoding.UTF8.GetString(buffer));
                    request.Body.Position = 0;
                }
                else if (request.Method.ToLower().Equals("get"))
                {
                    errorData.Add("Body", request.QueryString.Value);
                }
                _logger.LogInformation(JsonConvert.SerializeObject(errorData));
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                HttpRequest request = httpContext.Request;
                Dictionary<string, object> errorData = new Dictionary<string, object>();
                var trace = new StackTrace(ex, true);
                StackFrame frame = trace.GetFrames()[0];
                errorData.Add("MethodName", frame?.GetMethod().Name);
                errorData.Add("FileLineNumber", frame?.GetFileLineNumber());
                errorData.Add("URL", request.Path.ToString());
                errorData.Add("Method", request.Method);
                if (request.Method.ToLower().Equals("post"))
                {
                    request.EnableRewind();
                    Stream stream = request.Body;
                    byte[] buffer = new byte[request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    errorData.Add("Body", Encoding.UTF8.GetString(buffer));
                    request.Body.Position = 0;
                }
                else if (request.Method.ToLower().Equals("get"))
                {
                    errorData.Add("Body", request.QueryString.Value);
                }
                errorData.Add("ErrorInfo", ex.Message);
                _logger.LogError(JsonConvert.SerializeObject(errorData));
                await HandleExceptionAsync(httpContext, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
        {
            return httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new ResultMessage<string>() { success = true, data = null, message = ex.Message }));
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CustomExceptionMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomExceptionMiddleware>();
        }
    }
}
 

 

Startup类的  Configure 方法代码如下:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseCustomExceptionMiddleware();
            app.UseMvc();

        }

 

Program 类代码如下
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                //发布需要按以下配置
                .UseNLog())
               

 

 

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="internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="logs/${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />
  </targets>
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Debug" 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>

 类似资料: