Separate logging of multiple background services with dependency injection

65 views Asked by At

I have a issue, in my project i have 3 background services, and i need separate logging to 3 files, 1 back service - 1 log file.

The issue is what other classes injected by DI does not logging in log file of concrete background service.

That is, I want the service and all the objects inside this service to be logged into one file, in the context of one background service

Example, I have these classes:

  public class SimpleBackgroundService: BackgroundService
  {
      private readonly IServiceProvider _serviceProvider;
      private readonly ILogger<SimpleBackgroundService> _logger;

      private readonly ClientHandler _clientHandler;
      private readonly AddressHandler _addressHandler;
  }

  public class SeconSimpleBackgroundService: BackgroundService
  {
      private readonly IServiceProvider _serviceProvider;
      private readonly ILogger<SeconSimpleBackgroundService> _logger;

      private readonly TechnicalConnection _tcSoap;
      private readonly ClientHandler _clientHandler;
      private readonly AddressHandler _addressHandler;
  }

And I have these configs:

"Serilog": {
      "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async", "Serilog.Expressions" ],
      "MinimumLevel": {
        "Default": "Verbose",
        "Override": {
          "Microsoft": "Information",
          "Microsoft.AspNetCore": "Warning",
          "Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
          "System.Net.Http.HttpClient": "Warning"
        }
      },
      "WriteTo:Console": {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3} {SourceContext}] {Message:lj}{NewLine}{Exception}"
        }
      },
      "WriteTo": [
        {
          "Name": "Logger",
          "Args": {
            "configureLogger": {
              "Filter": [
                {
                  "Name": "ByIncludingOnly",
                  "Args": {
                    "expression": "SourceContext = 'Mtp.App.BackgroundServices.SecondSimpleBackgroundService'"
                  }
                }
              ],
              "WriteTo:Async": {
                "Name": "Async",
                "Args": {
                  "configure": [
                    {
                      "Name": "File",
                      "Args": {
                        "path": "./logs/temp_log.json",
                        "rollingInterval": "Day",
                        "rollOnFileSizeLimit": true,
                        "fileSizeLimitBytes": 20971520,
                        "retainedFileCountLimit": 50,
                        "formatter": {
                          "type": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        },
        {
          "Name": "Logger",
          "Args": {
            "configureLogger": {
              "Filter": [
                {
                  "Name": "ByIncludingOnly",
                  "Args": {
                    "expression": "SourceContext = 'Mtp.App.BackgroundServices.SimpleBackgroundService'"
                  }
                }
              ],
              "WriteTo:Async": {
                "Name": "Async",
                "Args": {
                  "configure": [
                    {
                      "Name": "File",
                      "Args": {
                        "path": "./logs/temp_log.json",
                        "rollingInterval": "Day",
                        "rollOnFileSizeLimit": true,
                        "fileSizeLimitBytes": 20971520,
                        "retainedFileCountLimit": 50,
                        "formatter": {
                          "type": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        },
        {
          "Name": "Logger",
          "Args": {
            "configureLogger": {
              "Filter": [
                {
                  "Name": "ByIncludingOnly",
                  "Args": {
                    "expression": "StartsWith(SourceContext,'Mtp.App.Handlers')"
                  }
                }
              ],
              "WriteTo:Async": {
                "Name": "Async",
                "Args": {
                  "configure": [
                    {
                      "Name": "File",
                      "Args": {
                        "path": "./logs/handlers_log_.json",
                        "rollingInterval": "Day",
                        "rollOnFileSizeLimit": true,
                        "fileSizeLimitBytes": 20971520,
                        "retainedFileCountLimit": 50,
                        "formatter": {
                          "type": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        },
      ]
    }

I tried make config by Including and StartsWith but has no luck

1

There are 1 answers

0
Qiang Fu On

Firstly you could try configure the settings in program.cs like below to see if it works.

var logger = new LoggerConfiguration()
    .WriteTo.Logger(l => l
            .Filter.ByIncludingOnly(Matching.FromSource<SimpleBackgroundService>())
            .WriteTo.File("Simple.log"))
    .CreateLogger();
builder.Services.AddSerilog(logger);

Then for appsettings expression you need to install package Serilog.Expressions to make expressions works then use "contains" instead.

            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "Contains(SourceContext, 'SimpleBackgroundService')"
                }
              }
            ],

Another thing to mention is your service name is SeconSimpleBackgroundService but you write "SecondSimpleBackgroundService" in the configruation file.