Asp.net Core 2.1 日志记录

nef*_*tus 5 c# logging asp.net-core-mvc asp.net-core

我想了解 asp.net cortex 2.1 上的登录问题。我的目标是记录所有可能导致 kestrel 服务器崩溃的严重错误。据我从文档 Microsoft.Extensions.Logging 和 Serilog 中了解到,您需要在每个控制器中创建一个记录器,并设置记录条件(例如 try/catch)。是否有一种更方便的方法可以从一个地方记录项目中的任何关键错误?我将不胜感激任何帮助。

Voo*_*doo 3

您可以创建一个Exception Middleware. 请参阅有关中间件的文档

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Threading.Tasks;

namespace API.Middlewares
{
    /// <summary>
    /// Custom Exception middleware to catch unhandled exception during runtime
    /// </summary>
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _logger = logger;
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                // next request in pipeline
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                // Logs your each error
                _logger.LogError($"Something went wrong: {ex}");
                await HandleExceptionAsync(httpContext, ex);
            }
        }

        /// <summary>
        /// Handle runtime error
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            // Customise it to handle more complex errors
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            return context.Response.WriteAsync($"Something went wrong: {exception.Message}");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到您的Startup.cs

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Custom exception middleware
            app.UseMiddleware<ExceptionMiddleware>();;

            app.UseMvc();
        }
Run Code Online (Sandbox Code Playgroud)

根据文档

在 Startup.Configure 方法中添加中间件组件的顺序定义了请求时调用中间件组件的顺序以及响应的相反顺序。

因此,请始终添加Exception Middleware为您的第一个中间件,以便它也可以捕获其他中间件的异常。