How do I write logs from within Startup.cs?

前端 未结 10 1377
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  萌比男神i
    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()
                .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();
            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

提交回复
热议问题