Asp.net core uses log4net global log processing

Time:2021-8-30

1、 Reference class library:

  1、 Microsoft.Extensions.Logging.Log4Net.AspNetCore

  2、log4net.AspNetCore

2、 Configure log4net.config file

3、 Create your own myexceptionfilterattribute and inherit it   Exceptionfilterattribute is an abstract class that relies on the injection log object   logger

public class MyExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger _logger;        
        /// 
        ///Through the constructor, dependency injection log objects
        /// 
        /// 
        public MyExceptionFilterAttribute(ILogger logger)
        {
            this._logger = logger;
        }
        public override void OnException(ExceptionContext context)
        {
            //Determine whether it has been processed
            if (!context.ExceptionHandled)
            {
                context.ExceptionHandled = true;
                Var STR = $"exception: {context. Httpcontext. Request. Path} {context. Exception. Message}";
                //Output to console
                Console.WriteLine(str);
                //Write text log (or record to database...)
                _logger.LogWarning(str);
                if (context.HttpContext.Request.Method == "GET")
                {
                    //If it is a get request, jump to the page
                }
                else
                {
                    //If it is a post, it is all an Ajax request. The JSON data format is returned and the custom or agreed format is output
                    Context. Result = new jsonresult (New {result = false, message = "there is an error in the request, please contact the administrator"});
                }
            }
        }
    }

4、 Use log4net in program.cs configuration

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging((context, loggingBuilder) =>
            {
                loggingBuilder.AddFilter("System", LogLevel.Warning);
                loggingBuilder.AddFilter("Microsoft", LogLevel.Warning);
                //Using log4net
                loggingBuilder.AddLog4Net();
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                });
    }

5、 Register the global filters error log processing in the startup.cs configureservices method

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews(options=> 
            {
                //Global registration, global validation
                options.Filters.Add(typeof(MyExceptionFilterAttribute));
            });
        }

In this way, the system can handle exceptions uniformly. Avoid the phenomenon that try catches are everywhere in the code, there are many developers, the written log format is not unified, and the error log is omitted.