gpt4 book ai didi

c# - ASP.NET Core Web App 将 404 请求记录为警告

转载 作者:行者123 更新时间:2023-11-30 17:26:24 24 4
gpt4 key购买 nike

如果我使用 dotnet new mvc 创建一个新的 ASP.NET Core Web App (Model-View-Controller),它已经配置了开箱即用的日志记录。

但是,http 请求错误代码被记录为信息事件。

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET https://localhost:5001/doesnotexists
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 4.4052ms 404

是否可以将此行为更改为(4xx -> 警告,5xx -> 错误)。即通过调查和重写日志事件。

我已经阅读了 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2

这看起来很有希望,但我没有找到用于此目的的钩子(Hook)

    var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureLogging((hostingContext, logging) =>
{
// investigate and rewrite log event
})
.UseStartup<Startup>()
.Build()

最佳答案

单行解决方案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using Microsoft.Extensions.Logging;

namespace temp
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostEnvironment env, ILogger<Startup> logger)
{

...

app.UseStatusCodePages(async context =>
{
var code = context.HttpContext.Response.StatusCode;
if (code == 404) {
logger.Log(LogLevel.Error, null, "log message");
}
});

...

}
}
}

关于c# - ASP.NET Core Web App 将 404 请求记录为警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56731883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com