Search code examples
loggingserilog

How do I use a property value in serilog log file name?


If I have the following code:

.WriteTo.Logger(c =>
    c.Filter.ByIncludingOnly(Matching.WithProperty("tsBatchStarted"))
        .WriteTo.File(
            path: Path.Combine(
                      baseDir,
                      "App_Data",
                      "logs",
                      $"SERCrawlerLog_{tsBatchStarted}.txt")
            , restrictedToMinimumLevel: LogEventLevel.Information
            , outputTemplate: logTextTemplate
            //, rollingInterval: RollingInterval.Day
            , retainedFileCountLimit: 2
            , shared: true
) // end .WriteTo.Logger(c =>

I would like to have the property's value for tsBatchStarted in the file name...

How do I use an event's property value in the serilog's log file name?


Solution

  • dotnet add package Serilog.Sinks.Map
    

    Then:

        .WriteTo.Logger(c => c
            .Filter.ByIncludingOnly(Matching.WithProperty("tsBatchStarted"))
            .WriteTo.Map(
                "tsBatchStarted",
                "none",
                (tsBatchStarted, wt) => wt.File(
                    path: Path.Combine(
                          baseDir,
                          "App_Data",
                          "logs",
                          $"SERCrawlerLog_{tsBatchStarted}.txt"),
                    restrictedToMinimumLevel: LogEventLevel.Information,
                    outputTemplate: logTextTemplate,
                    shared: true
                ),
                sinkMapCountLimit: 2
            )
        ) // end .WriteTo.Logger(c =>
    

    Note that this won't cause files to roll, you'll need to use an app based mechanism to clean up logs from old batches.