Dispatching Serilog events on a property value
Hey! You need to write log events to different locations based on where the event came from, its level, or some piece of data attached to it? Google/Stack Overflow/Gitter/GitHub in despair no more: the package you’re looking for is Serilog.Sinks.Map:
Log.Logger = new LoggerConfiguration()
.WriteTo.Map("Name", (name, wt) => wt.File($"log-{name}.txt"))
.CreateLogger();
Log.Information("Hello, {Name}!", "Alice");
// -> Event written to log-Alice.txt
Log.Information("Hello, {Name}!", "Bob");
// -> Event written to log-Bob.txt
Log.CloseAndFlush();
The first argument to Map()
is the name of the property to dispatch on. The second argument configures where to send events having a particular value for the property.
WriteTo.Map()
has an overload for computing the map key based on the LogEvent
with a function - e.g. le => le.Level
- and another for mapping non-string
properties to keys. More details in the README.
I thought I’d pen this quick note because, as with any substantial piece of software, there are many, many scenarios people have worked to accommodate in Serilog: tracking them down when you need them is the challenge! I’m going to put a bit of effort in over the next few weeks to surface the things that pop up regularly in questions from devs using Serilog and/or Seq; if you’ve got favourite features that need a signal boost, let me know!