2

I'm trying to configure Serilog in a .NET 5 WebApi project.

I can't figure out why everyone is injecting Serilog in Program.cs, and not in the Startup.cs file like this:

public void ConfigureServices(IServiceCollection services)
        {
            // inject serilog logger.
            services.AddScoped<ILogger>(factory =>
            {
                return new LoggerConfiguration()
                            .WriteTo.File(@"C:\mylogs\log.txt", rollingInterval: RollingInterval.Day)
                            .CreateLogger();

            });

            services.AddControllers();
        }
konkri
  • 186
  • 2
  • 12
  • 1
    Could you give an example of everyone doing it in Program.cs? Because I do it in Startup.cs. Maybe I'm wrong too, so I'm curious as to where you're seeing alternatives. – gilliduck Apr 21 '21 at 18:03
  • Hi, all I can find are these steps: https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/ – konkri Apr 21 '21 at 18:05

1 Answers1

2

If you register Logger in DI instead of configuring ILoggerFactory, you're not guaranteed that all your dependencies will use the one you registered in the startup.cs.

In the below issue, it's exactly what happened when OP configured that in the startup.cs .Net Core EventLog - override unhandled exception are written to Application log

Michal Rosenbaum
  • 1,801
  • 1
  • 10
  • 18