How do I write logs from within Startup.cs?

前端 未结 10 1416
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 04:16

In order to debug a .NET Core app which is failing on startup, I would like to write logs from within the startup.cs file. I have logging setup within the file that can be u

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 04:39

    For .NET Core 3.0 the official docs has this to say: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.0#create-logs-in-startup

    Writing logs before completion of the DI container setup in the Startup.ConfigureServices method is not supported:

    • Logger injection into the Startup constructor is not supported.
    • Logger injection into the Startup.ConfigureServices method signature is not supported

    But as they say in the docs you can configure a service that depends on ILogger, so if you wrote a class StartupLogger:

    public class StartupLogger
    {
        private readonly ILogger _logger;
    
        public StartupLogger(ILogger logger)
        {
            _logger = logger;
        }
    
        public void Log(string message)
        {
            _logger.LogInformation(message);
        }
    }
    

    Then in Startup.ConfigureServices add the service, then you need to build the service provider to get access to the DI container:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(provider =>
        {
            var service = provider.GetRequiredService>();
            return new StartupLogger(service);
        });
        var logger = services.BuildServiceProvider().GetRequiredService();
        logger.Log("Startup.ConfigureServices called");
    }
    

    Edit: this produces a compiler warning, for the sake of debugging your StartUp class this should be OK but not for production:

    Startup.cs(39, 32): [ASP0000] Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

提交回复
热议问题