首页 > 解决方案 > 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()

标签: c#asp.netasp.net-corelogging

解决方案


单线解决方案

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

            ...

        }
    }
}

推荐阅读