• 自定义ASP.NET Core日志中间件


      这个日志框架使用的是ASP.NET Core的NLog,用来记录每次请求信息和返回信息。

    1.首先创建一个Web应用项目,我选择的是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配置文件,内容如下:

        

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

    5.接下来开始自定义中间件

      添加一个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());
            }
        }

      再创建一个LogMiddlewareExtensions类:

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

      这样就编写好一个自定义的中间件。

    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文件下生成日志文件。

  • 相关阅读:
    java的构造方法 java程序员
    No result defined for action cxd.action.QueryAction and result success java程序员
    大学毕业后拉开差距的真正原因 java程序员
    hibernate的回滚 java程序员
    验证码 getOutputStream() has already been called for this response异常的原因和解决方法 java程序员
    浅谈ssh(struts,spring,hibernate三大框架)整合的意义及其精髓 java程序员
    你平静的生活或许会在某个不可预见的时刻被彻底打碎 java程序员
    Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下 java程序员
    poj1416Shredding Company
    poj1905Expanding Rods
  • 原文地址:https://www.cnblogs.com/afei-24/p/10744297.html
Copyright © 2020-2023  润新知