How do I write logs from within Startup.cs?

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

    Option 1: Directly use log (e.g. Serilog) in startup-

    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "Serilog-{Date}.txt"))
               .CreateLogger();
    
            Log.Information("Inside Startup ctor");
            ....
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            Log.Information("ConfigureServices");
            ....
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            Log.Information("Configure");
            ....
        }
    

    Output:

    To setup Serilog in asp.net-core application, check out the Serilog.AspNetCore package on GitHub.


    Option2: Configure logging in program.cs like this-

    var host = new WebHostBuilder()
                .UseKestrel()
                .ConfigureServices(s => {
                    s.AddSingleton();
                })
                .ConfigureLogging(f => f.AddConsole(LogLevel.Debug))
                .UseStartup()
                .Build();
    
    host.Run();
    

    User loggerFactory in startup like this-

    public class Startup
    {
        ILogger _logger;
        IFormatter _formatter;
        public Startup(ILoggerFactory loggerFactory, IFormatter formatter)
        {
            _logger = loggerFactory.CreateLogger();
            _formatter = formatter;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            _logger.LogDebug($"Total Services Initially: {services.Count}");
    
            // register services
            //services.AddSingleton();
        }
    
        public void Configure(IApplicationBuilder app, IFormatter formatter)
        {
            // note: can request IFormatter here as well as via constructor
            _logger.LogDebug("Configure() started...");
            app.Run(async (context) => await context.Response.WriteAsync(_formatter.Format("Hi!")));
            _logger.LogDebug("Configure() complete.");
        }
    }
    

    Complete details available on this link

提交回复
热议问题