Search code examples
dependency-injection.net-6.0serilogserilog-sinks-file

Injected Serilog does log to Debug, but not File


I'm trying to use Serilog with DI in my .NET 6 application. I have Serilog configured like this:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.Debug()
    .WriteTo.File(@"D:\log.txt",
                  retainedFileCountLimit: 5,
                  rollingInterval: RollingInterval.Day)
    .CreateLogger();

and my generic Host using

IHostBuilder host = new HostBuilder().UseSerilog(Log.Logger).Build()

(configuration and service-addidtion not shown here for brevity).

In my service-classes I require an ILogger from the Microsoft.Extensions.Logging Package. Now, the Problem I have is that I get correct Logging to Debug from everywhere, but the File-Sink only logs when I use Serilogs Log.Debug() Method for example.

If I comment out the "UseSerilog()" on the Hostbuilder I get no logging in Debug also. So Injection of Serilog to ILogger seems to work.

Any Ideas whats happening here ?


Solution

  • So it turns out it was a rather stupid mistake (for anyone interested). Somehow I thought this was a good Idea:

    try {
      Log.Debug("Starting Hostbuild");
      BuildHost();
    }
    catch (Exception ex)
    {
      Log.Fatal(ex, "Hostbuild Failed unexpectedly");
      return;
    }
    finally
    {
      Log.CloseAndFlush();
    }
    

    Which of course reset my Serilog Logger (Log) to default after the Hostbuild was done in BuildHost().

    I think I read somewhere that you're supposed to call CloseAndFlush at the end, but then changed where my "end" was...