AspCore 2.x - 自定义LoggerProvider

时间:2017-09-22 13:41:03

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

将核心更新到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。 也许有人知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 首先,我们添加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中注册记录器

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