Core统一日志处理

新建一个Core的Web项目,然后创建相关文件等

添加一个处理错误的类库ErrorMiddleware   下面是该类库的代码

public class ErrorMiddleware
    {
        static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly RequestDelegate next;
        public ErrorMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context /* other dependencies */)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                ErrorExceptionAsync(context, ex);
            }
        }

        private static void ErrorExceptionAsync(HttpContext context, Exception error)
        {
            var statusCode = (int)HttpStatusCode.InternalServerError;
            if (error is UnauthorizedAccessException)
            {
                // to prevent login prompt in IIS
                // which will appear when returning 401.
                statusCode = (int)HttpStatusCode.Forbidden;
            }
            if (statusCode != 404 && statusCode != 403)
            {
                logger.Error(error);
            }
        }
    }

到这里标红的两个是需要注意的 

RequestDelegate是一种委托类型,其全貌为public delegate Task RequestDelegate(HttpContext context),MSDN上对它的解释,"A function that can process an HTTP request."——处理HTTP请求的函数。唯一参数,是最熟悉不过的HttpContext,返回值则是表示请求处理完成的异步操作类型。

可以将其理解为ASP.NET Core中对一切HTTP请求处理的抽象(委托类型本身可视为函数模板,其实现具有统一的参数列表及返回值类型),没有它整个框架就失去了对HTTP请求的处理能力。

Invoke这个我们后面再说
现在我们需要跑起来项目 在Startup 下面的Configure里加上如下代码
 app.UseMiddleware(typeof(ErrorMiddleware));
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

然后全局的日志就可以在ErrorMiddleware这个类库里查看报错了   其中

Invoke 这个名字是不可以改变的  它是一个中间件调用 改了就会报错!!!
 

猜你喜欢

转载自www.cnblogs.com/fangyyy/p/10324595.html
今日推荐