简体   繁体   English

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

[英]ASP.NET Core Web App log 404 requests as warning

If I create a new ASP.NET Core Web App (Model-View-Controller) with dotnet new mvc it has already logging configured out of the box.如果我使用dotnet new mvc创建一个新的ASP.NET Core Web App (Model-View-Controller) ,它已经配置了开箱即用的日志记录。

However, http request error codes are logged as info event.但是,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

Is it possible to changed this behaviour to (4xx -> warning, 5xx -> error) .ie by investigating and rewriting log events.是否可以通过调查和重写日志事件将此行为更改为 (4xx -> warning, 5xx -> error) .ie。

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

this looked promissing but I didn't find a hook for this purpose这看起来很有希望,但我没有找到用于此目的的钩子

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

Single line solution单线解决方案

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

            ...

        }
    }
}

You need to implement your own ILogger and ILoggerProvider .您需要实现自己的ILoggerILoggerProvider

A simple demo like:一个简单的演示,如:

  1. CustomLogger

     public class CustomLogger : ILogger { public CustomLogger() { } public IDisposable BeginScope<TState>(TState state)=> NullScope.Instance; public bool IsEnabled(LogLevel logLevel) => true; public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter ) { var msg = formatter(state, exception); if (msg.Contains("404")) { logLevel = LogLevel.Warning; } Console.WriteLine($"{ GetLogLevelString(logLevel) } : { eventId } { msg } { exception }"); } private static string GetLogLevelString(LogLevel logLevel) { switch (logLevel) { case LogLevel.Trace: return "trce"; case LogLevel.Debug: return "dbug"; case LogLevel.Information: return "info"; case LogLevel.Warning: return "warn"; case LogLevel.Error: return "fail"; case LogLevel.Critical: return "crit"; default: throw new ArgumentOutOfRangeException(nameof(logLevel)); } } }
  2. CustomLoggerProvider

     public class CustomLoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) { return new CustomLogger(); } public void Dispose() { } }
  3. Register above code注册上面的代码

     public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(config => { config.ClearProviders(); config.AddProvider(new CustomLoggerProvider()); });

    You could check Logging and implement your own log provider.您可以检查Logging并实现您自己的日志提供程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core MVC 请求返回 404 - ASP.NET Core MVC requests return 404 尝试从 ASP.NET Core 5 Web 应用程序运行 Api 控制器功能时找不到 404 - 404 not found when trying to run Api Controller function from ASP.NET core 5 web app Asp.Net Core WEB API 错误 404 调用方法 - Asp.Net Core WEB API error 404 calling method 覆盖 404 在 Asp.Net 核心 Web API 中找不到 - Override 404 Not found in Asp.Net core Web API 未找到返回 404 的 Asp.Net Core“Web API”路由 - Asp.Net Core "Web API" Routes Returning 404 Not Found 如何在ASP.NET Core 1.0中显示Web应用程序的LoggerFactory日志控制台? - How to display the LoggerFactory log console in ASP.NET Core 1.0 for a web app? 如何在 asp.net 核心网络应用程序中登录文件 - 没有任何第三方工具 - How to log to a file in asp.net core web app - wtihout any third party tools ASP.NET 核心 Web API - 创建自定义请求和响应 - ASP.NET Core Web API - Create Custom Requests and Responses ASP.Net Core Web API 捕获用于日志记录的 HTTP 请求 - ASP.Net Core Web API Capturing HTTP Requests for Logging 在 asp.net 核心控制台应用程序中使用 log4net 进行日志记录 - Logging with log4net in asp.net core console app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM