c# - ASP.NET Core Web App 将 404 请求记录为警告
问题描述
如果我创建一个新ASP.NET Core Web App (Model-View-Controller)
的,dotnet new mvc
它已经配置了开箱即用的日志记录。
但是,http 请求错误代码被记录为 info 事件。
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 -> warning, 5xx -> error) 。
我已经阅读了https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2
这看起来很有希望,但我没有找到为此目的的钩子
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# - 在 LDAP 搜索中转义值
- go - go中如何与UDP服务器中的多个客户端通信?
- ruby - 使用 ruby Telegram 机器人发送消息的示例方法的概率
- sqlite - SQLITE 增加最大列数
- javascript - 隐藏值分配给 js 变量
- reactjs - 如何通过 Jenkins 从 Docker 容器中获取构建目录?
- c++ - 在 boost 日志中包含线程名称
- sql - 选择列过滤困难
- spring - 引起:java.lang.ClassNotFoundException:io.github.resilience4j.circuitbreaker.CircuitBreakerOpenException
- c# - 变量不覆盖 C#