日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

ASP.NET?Core使用自定義日志中間件_實(shí)用技巧

作者:Ruby_Lu ? 更新時(shí)間: 2022-06-13 編程語言

這個(gè)日志框架使用的是ASP.NET Core的NLog,用來記錄每次請(qǐng)求信息和返回信息。

1.首先創(chuàng)建一個(gè)Web應(yīng)用項(xiàng)目,我選擇的是MVC模板:

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

3.修改Configure方法:

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配置文件,內(nèi)容如下:

<?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>

注意:運(yùn)行項(xiàng)目時(shí)需要復(fù)制nlog.config到debug

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

添加一個(gè)LogMiddleware類:

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());
        }
    }

再創(chuàng)建一個(gè)LogMiddlewareExtensions類:

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

這樣就編寫好一個(gè)自定義的中間件。

6.在Configure方法中調(diào)用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?}");
            });
        }

運(yùn)行代碼,會(huì)在debug文件下生成日志文件。

原文鏈接:https://www.cnblogs.com/afei-24/p/10744297.html

欄目分類
最近更新