c# - Asp.net Core 2.1 日志记录

标签 c# asp.net-core logging asp.net-core-mvc

我想了解登录asp.net cortex 2.1的问题。我的目标是注册所有可能导致 kestrel 服务器中断的严重错误。正如我从文档中了解到的
Microsoft.Extensions.Logging
而Serilog,则需要在每个 Controller 中创建一个logger,并设置记录条件(例如try/catch)。有没有更方便的方法来从一个地方记录项目中的任何关键错误?我会很乐意提供任何帮助。

最佳答案

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

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

然后将其添加到您的 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();
        }

根据 DOCS

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response.



所以总是加Exception Middleware作为您的第一个 中间件 ,以便它可以捕获来自其他 的异常中间件 还。

关于c# - Asp.net Core 2.1 日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60388868/

相关文章:

c# - 尝试激活 'Microsoft.AspNetCore.Identity.SignInManager` 时无法解析类型 'xxxxx.LoginModel' 的服务

android - 日志消息在简单的 while(i<n){Log(i++)} 中丢失

javascript - 出现时将对象传递给模态

c# - ajax.abort() 的 ASP.NET MVC 解决方法

c# - 谁能告诉我为什么这个 C# 电子邮件验证正则表达式 (regex) 挂起?

c# - 类库(包)中的 Rijndael 不适用于 .NET Core

c# - 如何在特定时间触发.NET Core 3.1 Hosted Service?

c# - 更新服务引用在 WCF 中不起作用

logging - .NET Core - 如何根据类别进行过滤?

WindowsAzure : Is it possible to set directory permissions within the web. 配置?