API-шлюз, использующий Ocelot и пытающийся добавить Nlog с интерфейсом

Я новичок в ядре.net и Ocelot. Я установил.net core 2.0 framework с ocelot для API-шлюза. К этому сервису я хочу добавить свой собственный Nlog с интерфейсом и сделать его доступным для инъекций из main.cs (у ocelot есть встроенный nlog, но это мне не подходит). Я упоминаю мой код ниже. Проблема в моем LogMessageClass.cs, когда я вставляю _log из конструктора, регистрация не удается.

      public class Program
        {
            private static INLogger _logger;
            public static void Main(string[] args)
           {
//setup logger
            var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
logger.Debug("init main"); // this works

 new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        config
                            .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                            .AddJsonFile("appsettings.json", true, true)
                            .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true,
                                true)
                            .AddJsonFile("ocelot.json")
                            .AddEnvironmentVariables();

                        _configuration = config.Build();

                    })
                    .ConfigureServices((builderContext, services) =>
                    {//set up log factory
                        _loggerFactory = new NLoggerFactory();
                        _configuration.GetSection("Logging").Bind(_loggerFactory);
                        services.AddSingleton<INLoggerFactory, NLoggerFactory>();
                        services.AddSingleton<INLogger, NLogger>();

                        //set up logger
                        services.AddSingleton<ILoggerFactory, LoggerFactory>();
                        services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
                        services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));


                        services.AddOcelot()
                            var serviceProvider = services.BuildServiceProvider();
                        var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();

                        //configure NLog
                        loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
                        NLog.LogManager.LoadConfiguration("nlog.config");
                        _pipelineHelper = serviceProvider.GetService<IPipelineHelper>();
                    })
                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                      //  logging.AddConsole();
                      //  logging.AddDebug();
                    })
                   .UseIISIntegration()
                    .Configure(app =>
                    {

                   })
                    .Build()
                    .Run();
           }
        }

В моем классе - test.cs

 public class Test
    {
private readonly INLogger _nLogger;
 public Test(INLogger nLogger)
        {
            _nLogger = nLogger;
        }
 public void Log()
        {
            _nLogger.Info("Log my message" ); // this fails
}

}

Примечание: 1. Ведение журнала из основного метода работает 2. Ведение журнала из тестового класса завершается неудачно

Я использую nlog.config и вход в текстовый файл.

Любая помощь приветствуется.

0 ответов

Другие вопросы по тегам