How do I write logs from within Startup.cs?

前端 未结 10 1251
伪装坚强ぢ
伪装坚强ぢ 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:45

    .Net Core 3.1

    Unfortunately, for ASP.NET Core 3.0, the situation is again a bit different. The default templates use the HostBuilder (instead of the WebHostBuilder) which sets up a new generic host that can host several different applications, not limited to web applications. Part of this new host is also the removal of the second dependency injection container that previously existed for the web host. This ultimately means that you won’t be able to inject any dependencies apart from the IConfiguration into the Startup class. So you won’t be able to log during the ConfigureServices method. You can, however, inject the logger into the Configure method and log there:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
    {
        logger.LogInformation("Configure called");
    
        // …
    }
    

    If you absolutely need to log within ConfigureServices, then you can continue to use the WebHostBuilder which will create the legacy WebHost that can inject the logger into the Startup class. Note that it’s likely that the web host will be removed at some point in the future. So you should try to find a solution that works for you without having to log within ConfigureServices.


    .NET Core 2.x

    This has changed significantly with the release of ASP.NET Core 2.0. In ASP.NET Core 2.x, logging is created at the host builder. This means that logging is available through DI by default and can be injected into the Startup class:

    public class Startup
    {
        private readonly ILogger<Startup> _logger;
    
        public IConfiguration Configuration { get; }
    
        public Startup(ILogger<Startup> logger, IConfiguration configuration)
        {
            _logger = logger;
            Configuration = configuration;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            _logger.LogInformation("ConfigureServices called");
    
            // …
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            _logger.LogInformation("Configure called");
    
            // …
        }
    }
    
    0 讨论(0)
  • 2020-12-01 04:46

    The official solution is currently to setup a local LoggerFactory like this:

        using var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.SetMinimumLevel(LogLevel.Information);
            builder.AddConsole();
            builder.AddEventSourceLogger();
        });
        var logger = loggerFactory.CreateLogger("Startup");
        logger.LogInformation("Hello World");
    

    See also: https://github.com/dotnet/aspnetcore/issues/9337#issuecomment-539859667

    0 讨论(0)
  • 2020-12-01 04:47

    In .NET Core 3.1, you can create a logger directly using LogFactory.

    var loggerFactory = LoggerFactory.Create(builder =>
    {
         builder.AddConsole();                
    });
    
    ILogger logger = loggerFactory.CreateLogger<Startup>();
    logger.LogInformation("Example log message");
    
    0 讨论(0)
  • 2020-12-01 04:49

    Main code:

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }
    
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
    

    CreateDefaultBuilder sets up a default console logger.

    ... configures the ILoggerFactory to log to the console and debug output

    Startup code:

    using Microsoft.Extensions.Logging;
    ...
    public class Startup
    {
        private readonly ILogger _logger;
    
        public Startup(IConfiguration configuration, ILoggerFactory logFactory)
        {
            _logger = logFactory.CreateLogger<Startup>();
            Configuration = configuration;
        }
    
        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)
        {
            _logger.LogInformation("hello stackoverflow");
        }
    

    I couldn't get the injection of an ILogger to work, but perhaps that's because it's not a controller. More info welcome!

    Refs:

    • https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1&tabs=aspnetcore2x
    0 讨论(0)
提交回复
热议问题