自定義ASP.NET Core日誌中間件

  這個日誌框架使用的是ASP.NET Core的NLog,用來記錄每次請求信息和返回信息。web

1.首先建立一個Web應用項目,我選擇的是MVC模板:app

  

 

2.使用NuGet添加Microsoft.Extensions.Logging和NLog.Extensions.Logging框架

3.修改Configure方法:async

  

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); //添加NLog
            NLog.LogManager.LoadConfiguration("nlog.config"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

4.添加nlog.config配置文件,內容以下:ui

    

<?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="Warn" internalLogFile="internal-nlog.txt">

  <!--define various log targets-->
  <targets>

    <!--write logs to file-->
    <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />

  </targets>

  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

  注意:運行項目時須要複製nlog.config到debugthis

5.接下來開始自定義中間件spa

  添加一個LogMiddleware類:debug

    

public class LogMiddleware { private readonly RequestDelegate _next; private readonly ILogger<LogMiddleware> _logger; public LogMiddleware(RequestDelegate next, ILogger<LogMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { _logger.LogInformation("Request Url:" + context.Request.Path +Environment.NewLine + "Body:" + context.Request.Body.ToString()); await _next.Invoke(context); _logger.LogInformation("Response Url:" + context.Request.Path + Environment.NewLine + "Body:" + context.Response.Body.ToString()); } }

  再建立一個LogMiddlewareExtensions類:日誌

/// <summary>
    /// 這是擴展中間件 /// </summary>
    public static class LogMiddlewareExtensions { public static IApplicationBuilder UseLog(this IApplicationBuilder builder) { return builder.UseMiddleware<LogMiddleware>(); } }

  這樣就編寫好一個自定義的中間件。code

6.在Configure方法中調用app.UseLog()

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); //添加NLog
            NLog.LogManager.LoadConfiguration("nlog.config"); app.UseLog(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

運行代碼,會在debug文件下生成日誌文件。

相關文章
相關標籤/搜索