ASP.NET Core Web App日志404请求为警告

时间:2019-06-24 07:40:19

标签: c# asp.net asp.net-core logging

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

但是,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://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()

2 个答案:

答案 0 :(得分:1)

您需要实现自己的ILoggerILoggerProvider

一个简单的演示,例如:

  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. 注册以上代码

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

    您可以检查Logging并实现自己的日志提供程序。

答案 1 :(得分:0)

单行解决方案

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

            ...

        }
    }
}