zoukankan      html  css  js  c++  java
  • netcore 中间件记录日志

    public class Logger
        {
            private static ILog logger;
           static Logger()
            {
                if (logger == null)
                {
                    var repository = LogManager.CreateRepository("NETCoreRepository");
                    //log4net从log4net.config文件中读取配置信息
                    XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
                    logger = LogManager.GetLogger(repository.Name, "Logger");
                }
            }
            private RequestDelegate _nextDelegate;
            public Logger(RequestDelegate nextDelegate)
            {
                _nextDelegate = nextDelegate;
            }
            public async Task Invoke(HttpContext httpContext)
            {
                logger.Info("start:" + DateTime.Now.ToString());
                await _nextDelegate.Invoke(httpContext);
                logger.Info("end:" + DateTime.Now.ToString());
            }
            public static void Info(string message, Exception exception = null)
            {
                if (exception == null)
                    logger.Info(message);
                else
                    logger.Info(message, exception);
            }
            public static void Warn(string message, Exception exception = null)
            {
                if (exception == null)
                    logger.Warn(message);
                else
                    logger.Warn(message, exception);
            }
            public static void Error(string message, Exception exception = null)
            {
                if (exception == null)
                    logger.Error(message);
                else
                    logger.Error(message, exception);
            }
        }

    然后,在startup.cs中增加

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseMiddleware<Logger>();
                app.UseMvc();
                
            }

    所有中间件需要放在UseMvc前面

    测试

  • 相关阅读:
    微信小程序~事件绑定和冒泡
    为promise增加abort功能
    Object构造函数的方法 之 Object.freeze
    ES6新特性:JavaScript中内置的延迟对象Promise
    js 预编译
    什么是PWA?PWA的发展趋势
    CSS隐藏元素的方法及区别
    网页编码:UTF-8、GB2312
    Mixin 和 CSS Guards
    css自定义checkbox样式
  • 原文地址:https://www.cnblogs.com/huanyun/p/11365197.html
Copyright © 2011-2022 走看看