.NetCore 3.1 Log4net 记录全局异常日志、api 日志

全局异常日志

  1. ExceptionMiddleware
    public class ExceptionMiddleware
    {
        private readonly ILogger logger;
        private readonly RequestDelegate next;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            this.logger = logger;
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception e)
            {
                await ExceptionHandlerAsync(context, e);
            }
        }

        private async Task ExceptionHandlerAsync(HttpContext context, Exception e)
        {
            context.Response.ContentType = "application/json";

            logger.LogError(e, context.Request.Path);

            var result = new Response<string>()
            {
                status = 500,
                msg = e.Message
            };

            await context.Response.WriteAsync(result.ToJson());
        }
    }
  1. Startup Configure
    app.UseMiddleware<ExceptionMiddleware>();

Api 日志

  1. ApiLogFilter
    public class ApiLogFilter : IAsyncActionFilter
    {
        private readonly ILogger logger;

        public ApiLogFilter(ILogger<ApiLogFilter> logger)
        {
            this.logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string actionArguments = context.ActionArguments.ToJson();

            var resultContext = await next();

            string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString;

            string method = resultContext.HttpContext.Request.Method;

            dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic;

            string response = JsonConvert.SerializeObject(result.Value);

            logger.LogInformation($"URL:{url} \n " +
                                  $"Method:{method} \n " +
                                  $"ActionArguments:{actionArguments}\n " +
                                  $"Response:{response}\n ");
        }
    }
  1. Startup ConfigureServices
    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(ApiLogFilter));
    });

日志

  1. Error Log
  1. Api Log

相关资料

  1. demo
posted @ 2020-07-18 23:00  仿佛若有光;  阅读(820)  评论(0编辑  收藏  举报