zoukankan      html  css  js  c++  java
  • 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 这个名字是不可以改变的  它是一个中间件调用 改了就会报错!!!
     
  • 相关阅读:
    css的三种方法以及优先级说明
    form表单中的label标签
    html 中 a 标签 mailto的用法
    Hexo + GitHub Pages搭建博客
    Sublime Text3使用指南
    IMU数据融合:互补,卡尔曼和Mahony滤波
    正点原子STM32探索者学习笔记4
    正点原子STM32探索者学习笔记3
    正点原子STM32探索者学习笔记2
    正点原子STM32探索者学习笔记1
  • 原文地址:https://www.cnblogs.com/fangyyy/p/10324595.html
Copyright © 2011-2022 走看看