【问题标题】:AspCore 2.x - custom LoggerProviderAsp Core 2.x - 自定义 ILoggerProvider
【发布时间】:2017-09-22 13:41:03
【问题描述】:

将核心更新到 2.x 后,我的 Logger 遇到了问题。 我需要记录一些有关请求的信息(URL、标头等)。 在 asp core 1.x 中,我创建了我的提供程序并在

中注册了它
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddAppLogger((n, l) => l >= LogLevel.Error || n.EndsWith("AppLogger", StringComparison.OrdinalIgnoreCase), app.ApplicationServices);
    }

我使用 app.ApplicationServices (IServiceProvider) 来获取 AppLogger 实例

var httpContext = _serviceProvider.GetService<IHttpContextAccessor>()?.HttpContext; 

但是更新后出现了问题,我看到在旧方案中没有创建我的记录器的实例。我读到在新版本中我们需要像这样注册 LoggerProvider

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddProvider(new AppLoggerProvider((n, l) => l >= LogLevel.Error || n.EndsWith("AppLogger", StringComparison.OrdinalIgnoreCase)));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

或者需要在 StartUp.cs 中使用 service.AddLogging 方法 但在这种情况下,我无法获得 IHttpContextAccessor 或 IServiceProvider。 我看到了其他流行记录器的代码,但他们没有使用 IHttpContextAccessor。 也许有人知道如何解决这个问题?

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    我找到了解决方案。 首先,我们添加 AppLoggerProvider

    public static class AppLoggerExtensions
    {
    
        public static ILoggingBuilder AddAppLogger(this ILoggingBuilder builder)
        {
    
            builder.Services.AddSingleton<ILoggerProvider, AppLoggerProvider>();
            return builder;
        }
    }
    

    我重写了我的记录器的构造函数,现在使用 IHttpContextAccessor :

        public AppLogger(string name, Func<string, LogLevel, bool> filter, IHttpContextAccessor httpContextAccessor = null)
        {
            this._name = string.IsNullOrEmpty(name) ? "AppLogger" : name;
            this._filter = filter;
            this._httpContextAccessor = httpContextAccessor;
        }
    

    然后我们在服务中注册func。

    public void ConfigureServices(IServiceCollection services)
            {
                // Add Logging logics
                services.AddSingleton(provider =>
                    new Func<string, LogLevel, bool>((n, l) => l >= LogLevel.Error || n.EndsWith("AppLogger", StringComparison.OrdinalIgnoreCase)));
            }
    

    并在 Programm.cs 中注册 logger

     public class Program
        {
            public static void Main(string[] args)
            {
                var host = new WebHostBuilder()
                    .UseKestrel(config => config.AddServerHeader = false)
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        var env = hostingContext.HostingEnvironment;
                        config.AddJsonFile("config\\appsettings.json", optional: true, reloadOnChange: true)
                            .AddJsonFile($"config\\appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                        config.AddEnvironmentVariables();
                    })
                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        // Add custom logger
                        logging.AddAppLogger();
    
                        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                        if (hostingContext.HostingEnvironment.IsDevelopment())
                        {
                            logging.AddDebug();
                        }
    
                    })
                    .UseStartup<Startup>()
    
                    .Build();
    
    
                host.Run();
            }
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2020-02-01
      • 2019-07-31
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多