1. 程式人生 > >.Net Core中介軟體和過濾器實現錯誤日誌記錄

.Net Core中介軟體和過濾器實現錯誤日誌記錄

1.中介軟體的概念

ASP.NET Core的處理流程是一個管道,中介軟體是組裝到應用程式管道中用來處理請求和響應的元件。 每個中介軟體可以:

  • 選擇是否將請求傳遞給管道中的下一個元件。
  • 可以在呼叫管道中的下一個元件之前和之後執行業務邏輯。

  中介軟體是一個請求委託( public delegate Task RequestDelegate(HttpContext context) )的例項,所以中介軟體的本質就是一個方法,方法的引數是HttpContext,返回Task。傳入的HttpContext引數包含了請求和響應資訊,我們可以在中介軟體中對這些資訊就行修改。中介軟體的管道處理流程如下:

  我們知道中介軟體是配置請求處理管道的元件,那麼誰來負責構建管道呢?負責構建管道的角色是ApplicationBuilder。ApplicationBuilder通過Use、Run、Map及MapWhen方法來註冊中介軟體,構建請求管道。我們簡單看下這幾個方法。

1 Run

  新建一個WebAPI專案,修改StartUp中的Configure方法如下,用Run方法註冊的中介軟體可以叫做終端中介軟體,即該中介軟體執行完成後不再執行後續的中介軟體。

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //第一個中介軟體
            app.Run(async (context) =>
            {
                context.Response.ContentType = "text/plain;charset=utf-8";//防止中文亂碼
                await context.Response.WriteAsync("第一個中介軟體輸出你好~");
            });
            //第二個中介軟體
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("第二個中介軟體輸出你好~");
            });
        }

  執行程式,我們看到只執行了第一個中介軟體,後邊的中介軟體不會執行。

2 Use

  Use方法的引數是一個委託例項,委託的第一個引數是HttpContext,這是待處理的請求上下文;第二個引數next是下一個中介軟體,我們可以通過next.Invoke()呼叫下一個中介軟體,並且可以在呼叫下一個中介軟體之前/之後對HttpContext做一個邏輯處理。

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //第一個中介軟體
            app.Use(async (context, next) =>
            {
                context.Response.ContentType = "text/plain;charset=utf-8";//防止中文亂碼
                await context.Response.WriteAsync($"第一個中介軟體輸出你好~{Environment.NewLine}");

                await context.Response.WriteAsync($"下一個中介軟體執行前執行===>{Environment.NewLine}");
                await next.Invoke();
                await context.Response.WriteAsync($"下一個中介軟體執行後執行<==={Environment.NewLine}");
            });
            //第二個中介軟體
            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync($"第二個中介軟體輸出你好~{Environment.NewLine}");
            });
        }

   執行程式如下所示。注意如果我們沒有呼叫next.Invoke()方法,會造成管道短路,後續的所有中介軟體都不再執行。

3 Map

  在業務簡單的情況下,使用一個請求處理管道來處理所有的請求就可以了,當業務複雜的時候, 我們可能考慮把不同業務的請求交給不同的管道中處理。 Map 基於給定請求路徑的匹配項來建立請求管道分支。 如果請求路徑以給定路徑開頭,則執行分支。看一個栗子,需求是/userinfo開頭的請求使用使用者分支管道來處理,/product開頭的請求使用產品分支管道處理,程式碼如下:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // 依賴注入
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        /// <summary>
        /// 配置使用者分支管道,處理以url以/userinfo開頭的請求 
        /// </summary>
        /// <param name="app"></param>
        private static void UserinfoConfigure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync($"處理使用者業務,{Environment.NewLine}");
                await next.Invoke();
            });
            app.Run(async (context) => { await context.Response.WriteAsync("使用者業務處理完成~"); });
        }
        /// <summary>
        /// 配置產品分支管道,處理以url以/product開頭的請求
        /// </summary>
        /// <param name="app"></param>
        private static void ProductConfigure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync($"處理產品業務");
                await next.Invoke();
            });
        }
        // 配置請求處理管道
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //防止中文亂碼
            app.Use(async (context,next) =>
            {
                context.Response.ContentType = "text/plain;charset=utf-8";
                await next.Invoke();
            });

            app.Map("/userinfo", UserinfoConfigure);

            app.Map("/product", ProductConfigure);

            app.Run(async context =>
            {
                await context.Response.WriteAsync("主管道處理其他業務");
            });
        }
    }

  執行程式執行結果如下:

4 MapWhen

  MapWhen和Map的思想比較相似,MapWhen基於自定義條件來建立請求管道分支,並將請求對映到管道的新分支。看一個栗子就明白了,下邊栗子的需求是查詢引數包含name的請求交給一個分支管道處理,url包含/userinfo的請求交給使用者分支來處理,程式碼如下:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // 依賴注入
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        /// <summary>
        /// 配置分支管道,處理以url中有包含/userinfo的請求
        /// </summary>
        /// <param name="app"></param>
        private static void UserinfoConfigure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync($"處理使用者業務,{Environment.NewLine}");
                await next.Invoke();
            });
            app.Run(async (context) => { await context.Response.WriteAsync("使用者業務處理完成~"); });
        }
        /// <summary>
        /// 配置分支管道,處理以查詢引數有name的請求
        /// </summary>
        /// <param name="app"></param>
        private static void HNameConfigure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync($"查詢引數包含name,值為:{context.Request.Query["name"]}");
                await next.Invoke();
            });
        }
        // 配置請求處理管道
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //防止中文亂碼
            app.Use(async (context,next) =>
            {
                context.Response.ContentType = "text/plain;charset=utf-8";
                await next.Invoke();
            });
          
            app.MapWhen(context => context.Request.Query.ContainsKey("name"), HNameConfigure);
            app.MapWhen(context => context.Request.Path.Value.ToString().Contains("/userinfo"), UserinfoConfigure);

            app.Run(async context =>
            {
                await context.Response.WriteAsync("主管道處理其他業務");
            });
        }
    }

   程式執行結果如下:

  到這裡我們對中介軟體已經有了一個基本的瞭解,接下了通過一個異常日誌 中介軟體來了解開發中怎麼去使用中介軟體。

2 使用中介軟體記錄錯誤日誌

  這裡使用的日誌元件為nlog,首先建立一個WebAPI專案,新增一個自定義日誌處理中介軟體CostomErrorMiddleware,當程式出錯時會記錄日誌,同時開發環境下會把異常的詳細資訊列印在頁面上,非開發環境隱藏詳細資訊,程式碼如下:

    /// <summary>
    /// 自定義的錯誤處理類
    /// </summary>
    public class CostomErrorMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger logger;
        private IHostingEnvironment environment;
        /// <summary>
        /// DI,注入logger和環境變數
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>
        /// <param name="environment"></param>
        public CostomErrorMiddleware(RequestDelegate next, ILogger<CostomErrorMiddleware> logger, IHostingEnvironment environment)
        {
            this.next = next;
            this.logger = logger;
            this.environment = environment;
        }
        /// <summary>
        /// 實現Invoke方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next.Invoke(context);
            }
            catch (Exception ex)
            {
                await HandleError(context, ex);
            }
        }
        /// <summary>
        /// 錯誤資訊處理方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private async Task HandleError(HttpContext context, Exception ex)
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/json;charset=utf-8;";
            string errorMsg = $"錯誤訊息:{ex.Message}{Environment.NewLine}錯誤追蹤:{ex.StackTrace}";
            //無論是否為開發環境都記錄錯誤日誌
            logger.LogError(errorMsg);
            //瀏覽器在開發環境顯示詳細錯誤資訊,其他環境隱藏錯誤資訊
            if (environment.IsDevelopment())
            {
                await context.Response.WriteAsync(errorMsg);
            }
            else
            {
                await context.Response.WriteAsync("抱歉,服務端出錯了");
            }
        }
    }

  修改StartUp類中的Configure方法如下,注入nlog 需要先安裝 NLog.Web.AspNetCore ,使用app.UseMiddleware<CostomErrorMiddleware>()註冊我們自定義的中介軟體,程式碼如下:

       /// 配置請求管道
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
        {
            //新增nlog
            factory.AddNLog();
            env.ConfigureNLog("nlog.config");
            //泛型方法新增中介軟體
            app.UseMiddleware<CostomErrorMiddleware>();
            app.UseMvc(); 
        }

nlog.config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile="D:\LogDemoOfWebapi\internal-nlog.txt">
  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <targets>
    <target xsi:type="File" name="errorLog" fileName="D:/logs/AT___${shortdate}.log" 
            layout="----------------日誌記錄開始----------------${newline}【日誌時間】:${longdate} ${newline}【日誌級別】:${level:uppercase=true}${newline}【異常相關資訊】${newline}${message}${newline}${newline}${newline}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Error" writeTo="errorLog" />
  </rules>
</nlog>
View Code

  到這裡異常處理中介軟體就註冊完成了,修改ValueController自己製造一個異常來測試一下,程式碼如下:

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private ILogger<ValuesController> _logger;
        public ValuesController(ILogger<ValuesController> logger)
        {
            _logger = logger;
        }
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
          
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            throw new Exception("有一個錯誤發生了..");
            return "value";
        }
    }

  執行程式,在開發環境下訪問/Values/1,顯示結果如下,同時這些錯誤資訊也會通過nlog寫入到錯誤日誌中:

   非開發環境下,訪問/values/1,顯示如下:

  如果我們想使用類似app.UseMvc()這樣的形式來使用我們自定義的中介軟體的話,就需要給ApplicationBuilder新增一個擴充套件方法,首先新增一個靜態類CostomMiddleware,程式碼如下:

    /// <summary>
    /// 擴充套件方法
    /// </summary>
    public static class CostomMiddleware
    {
        public static IApplicationBuilder UseCostomError(this IApplicationBuilder app)
        {
            return app.UseMiddleware<CostomErrorMiddleware>();
        }
    }

  然後修改Configure方法即可:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
        {
            //新增nlog
            factory.AddNLog();
            env.ConfigureNLog("nlog.config");
            //使用擴充套件方法
             app.UseCostomError();
            app.UseMvc(); 
        }

  執行程式後和前邊的執行效果是一樣的。

3 使用過濾器記錄錯誤日誌

  過濾器大家應該都很熟悉,在ASP.NET Core中過濾器的使用沒有太大的變化,這裡也實現一個使用過濾器記錄錯誤日誌的栗子,直接看程式碼吧,首先建立一個過濾器,程式碼如下:

    /// <summary>
    /// 自定義的錯誤處理過濾器
    /// </summary>
    public class CustomErrorFilter :Attribute, IExceptionFilter
    {
        private readonly ILogger _logger;
        private IHostingEnvironment _environment;

        public CustomErrorFilter(ILogger<CustomErrorFilter> logger,IHostingEnvironment environment)
        {
            
            _logger = logger;
            _environment = environment;
        }
        public void OnException(ExceptionContext context)
        {
            Exception ex = context.Exception;
            string errorMsg = $"錯誤訊息:{ex.Message}{Environment.NewLine}錯誤追蹤:{ex.StackTrace}";
            ContentResult result = new ContentResult
            {
                ContentType = "text/json;charset=utf-8;",
                StatusCode = 500
            };
            //無論是否為開發環境都記錄錯誤日誌
            _logger.LogError(errorMsg);
            //瀏覽器在開發環境顯示詳細錯誤資訊,其他環境隱藏錯誤資訊
            if (_environment.IsDevelopment())
            {
                result.Content = $"錯誤訊息:{ex.Message}{Environment.NewLine}錯誤追蹤:{ex.StackTrace}";
            }
            else
            {
                result.Content = "抱歉,服務端出錯了";
            }
            context.Result = result;
            context.ExceptionHandled = true;
        }
    }

  修改StartUp類,注入nlog,配置全域性過濾器,程式碼如下,其中nlog.config和中介軟體栗子中一樣:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // 依賴注入
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(
                configure =>
                {
                    configure.Filters.Add<CustomErrorFilter>();//全域性過濾器,不用新增特性頭
                }//全域性過濾器,不用新增特性頭
                ).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //services.AddScoped<CustomErrorFilter>();//區域性過濾器,需要在Controller/Action新增特性頭 [ServiceFilter(typeof(CustomErrorFilter))]
        }

        // 配置管道
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
        {
            factory.AddNLog();
            env.ConfigureNLog("nlog.config");
            app.UseMvc();
        }
    }

  然後修改ValuesController,設定錯誤和上邊中介軟體的栗子一樣,執行程式碼訪問/values/1時,在開發環境中顯示如下,同時錯誤資訊也會寫入錯誤日誌中:

   在生產環境中訪問/values/1的話,錯誤詳細也會寫入錯誤日誌中,瀏覽器顯示如下:

  本文介紹了中介軟體的基本使用,同時使用中介軟體和過濾器兩種方式實現了異常日誌的記錄,如果文中有錯誤的地方希望大家可以指出,我會及時改正。

參考文章

  【1】https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-3.0

  【2】https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0

  

&n