Home > OS >  How to use Serilog in .Net 6 console applcition
How to use Serilog in .Net 6 console applcition

Time:10-31

I am trying to add Serilog into .net 6 console application and inject it into other services. I have created this application using "Do not use top-level statements" option. That means I do not have an explicit main method in my program. I used the following code inorder to register Serilog

var config = new ConfigurationBuilder()
               .AddJsonFile("appSettings.json", false, true)
               .Build();



var serviceProvider = new ServiceCollection()
                      .AddLogging(builder =>
                      {
                          var logger = new LoggerConfiguration()
                                        .MinimumLevel.Information()
                                        .WriteTo.File(path: "\\Logs", restrictedToMinimumLevel: LogEventLevel.Information, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                                        fileSizeLimitBytes: 1000000, rollOnFileSizeLimit: true, retainedFileCountLimit: 365, retainedFileTimeLimit: new TimeSpan(365, 0, 0, 0))
                                        .CreateLogger();
                          builder.AddSerilog(logger);
                      })
                      .BuildServiceProvider();

var service = serviceProvider.GetService<Serilog.ILogger>();

I have added following nuget packages into my console application

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
    <PackageReference Include="Microsoft.Identity.Client" Version="4.47.2" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.9" />
    <PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
    <PackageReference Include="Serilog" Version="2.12.0" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
  </ItemGroup>

However, I cannot get the Serilog from the service provider object var service = serviceProvider.GetService<Serilog.ILogger>();. It always returns null.

CodePudding user response:

You'll have to configure the lifetime for ILogger

var serviceProvider = new ServiceCollection()
                  .AddLogging(builder =>
                  {
                      var logger = new LoggerConfiguration()
                                    .MinimumLevel.Information()
                                    .WriteTo.File(path: "\\Logs", restrictedToMinimumLevel: LogEventLevel.Information, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                                    fileSizeLimitBytes: 1000000, rollOnFileSizeLimit: true, retainedFileCountLimit: 365, retainedFileTimeLimit: new TimeSpan(365, 0, 0, 0))
                                    .CreateLogger();
                      builder.AddSerilog(logger);
                  })
                  //this is important
                  .AddSingleton<Serilog.ILogger>(sp =>
                  {
                      return new LoggerConfiguration()
                          .MinimumLevel.Debug()
                          .CreateLogger();
                  })
                  .BuildServiceProvider();
  • Related