Search code examples
c#serilog

Serilog sink wrapper mapping, separate filename from content


Using the Serilog.Sinks.Map library, the example shows

Log.Logger = new LoggerConfiguration()
    .WriteTo.Map("Name", "Other", (name, wt) => wt.File($"./logs/log-{name}.txt"))
    .CreateLogger();

Log.Information("Hello, {Name}!", "Alice");
Log.CloseAndFlush();

An event written to log-Alice.txt with text Hello, Alice!

How do I do similar but separate the filename from the content? Eg I want to do

Log.Information("Hello!", "Alice");

which should write to a file log-Alice.txt but with text Hello!

Essentially my goal is to log to any named log but there could be hundreds of them.


Solution

  • Serilog.Sinks.Map, in your example, is using a property called Name to define the file name. If you don't want to define this property in the message template, you can define it via Context, for example:

    var log = Log.ForContext("Name", "Alice");
    
    log.Information("Hello!");
    log.Information("Hello Again!");
    

    Both messages above would be written to the log-Alice.txt file, because they both carry a property Name = "Alice" in the log context.

    Similarly, the below will write each message to a separate file:

    Log.ForContext("Name", "John").Information("Hello 1!"); // log-John.txt
    Log.ForContext("Name", "Peter").Information("Hello 2!"); // log-Peter.txt