0

我正在开发一个.NET core 3.1 控制台应用程序 (web-api)。我使用Serilog服务(它基本上是使用 Microsoft.Extensions.Logging)。Serilog 被注入并且可以在 FW Controllers 方法中使用。现在 - 我需要一些不同的东西 - 每当系统启动时(在关闭后),我需要发出一个 http post 请求 - 你可以在启动方法中执行ConnectionInitiator.Initiate()时看到它。在同一范围内(方法\类) - 我需要使用记录器来记录一些数据。现在 - 如果请求将通过控制器 - 记录器将可用(由DI)。长话短说——我需要以某种方式将 Ilogger 注入课堂或以其他方式使其可用。我尝试在启动时使用记录器,但这似乎是不可能的(因为.net core 3.0 - 如果我理解正确的话)查看我的代码:

程序.cs:

public class Program
    {
        public static void Main(string[] args)
        {
            var loggerConfig = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
            //Reading the appconfig.json
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(loggerConfig).CreateLogger();
            try
            {
                Log.Information("System Started up");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "THE APPLICATION FAILED TO START UP");
            }
            finally
            {
                Log.CloseAndFlush();
            }

        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args).ConfigureLogging((context, logging) =>
            {
                logging.ClearProviders();
            }).UseSerilog().UseStartup<Startup>();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

启动.cs

public class Startup
{
    public Startup(IConfiguration configuration/*, Microsoft.Extensions.Logging.ILogger logger*/)
    {
        Configuration = configuration;
        ConnectionInitiator.Initiate(configuration/*, logger*/);
    }


    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddControllers();
        services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed((host) => true).AllowCredentials());
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();
        app.UseAuthentication();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

ConnectionInitiator.cs:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

using System.Threading.Tasks;

namespace AAA.BL
{
    public static class ConnectionInitiator
    {

        private static readonly object threadlock = new object();
        private static MyConfig myConfig;
        private static ILogger ilogger;
        /*
        public ConnectionInitiator(ILogger _logger)
        {
            ilogger = _logger;
        }
        */
        public static void/*async Task*/ Initiate(IConfiguration configuration/*, ILogger ilogger*/)
        {
            HttpRequester httpRequester = new HttpRequester();
            if (myConfig == null)
            {
                myConfig = new myConfig(configuration);
            }

            IssueOTPResponse response = /*await*/ httpRequester.PostSomething(myConfig, ilogger).Result;            //Double check thread safe singleton implementation
            if (response.ststuacode != 200)
            {
                ilogger.logcritical($"critical error when initiate connection (connectioninitiator): {response.statusdescription}");
            }

        }
    }
}
4

1 回答 1

0

似乎答案比我预期的要简单得多 - 通过使用Serilog并在Configure方法中作为服务添加 - 可以通过使用静态类 Log 及其静态方法在全局范围内(在名称空间的每个地方)访问它记录器,例如:Log.Logger.Information("XXXXX");

于 2021-05-26T12:56:05.610 回答