serilog-generator.exe and fun with key-value settings
Some things are just fun to build, and without much concern for its general utility I thought I’d share one of them :-)
serilog-generator.exe is a handy little app for exercising Serilog sinks and log servers without needing a test harness project for each one. It’s published on NuGet as a ‘tools’ package and can be installed into a sink project like any other NuGet package:
Install-Package serilog-generator
(It’s also on Chocolatey but currently fails because of some command-line handling that Chocolatey shims seem to do.)
At a command prompt in a folder containing a Serilog sink assembly, the sink can be loaded, configured, and sample data pushed through it with a command-line like this one that exercises the Seq sink:
serilog-generator --using="Serilog.Sinks.Seq" --write-to:Seq.serverUrl="http://localhost:5341"
Unless --quiet
is specified, the log will also be written to the console so you can compare it with what shows up in your sink:
You might have noticed that the command-line syntax for configuring the sink is very similar to the `` format supported by Serilog 1.5. Compare the command-line above with:
<appSettings>
<add key="serilog:using" value="Serilog.Sinks.Seq" />
<add key="serilog:write-to:Seq.serverUrl" value="http://localhost:5341" />
</appSettings>
The XML version uses a serilog:
prefix to disambiguate from other settings often found in config files, but apart from that you can see the basic using
/write-to
directives (as well as the minimum-level
and enrich
options not shown here) work the same way.
That’s because the underlying Serilog configuration support is key-value based, not specific to XML settings files. You can read Serilog configuration from any medium that can represent key-value pairs.
Adding a new configuration provider is as easy as finding a way to load the pairs:
var pairs = new Dictionary
{
{ "using", "Serilog.Sinks.Seq" },
{ "write-to:Seq.serverUrl", "http://localhost:5341" }
});
Log.Logger = new LoggerConfiguration()
.ReadFrom.KeyValuePairs(pairs)
.CreateLogger();
You can see how serilog-generator.exe
uses this general support to implement ReadFrom.CommandLine()
in its source. There are a couple of subtle points in there but it’s really only a few lines of code.
Reading settings from the command-line might not be particularly useful for many (most!) apps, but if you’re using a different configuration system and want to tap into Serilog’s built-in settings support it can come together quite smoothly.