我想了解登录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/