简体   繁体   中英

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.

However, http request error codes are logged as info event.

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.

I already read 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM