Unfortunately Serilog does not expose the list of Sinks that have been configured, so your only option at the moment would be to use Reflection.
If you poke around Serilog's source code, you'll see that it groups all configured sinks into an instance of an internal class SafeAggregateSink
which is responsible emitting the logs to the different sinks setup, and holds an array with all the configured sinks in a private field called _sinks
.
Here is a simple example:
var log = new LoggerConfiguration()
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Verbose)
.WriteTo.File(path: "log.txt", restrictedToMinimumLevel: LogEventLevel.Verbose)
.CreateLogger();
var aggregateSinkFieldInfo = log.GetType()
.GetField("_sink", BindingFlags.Instance | BindingFlags.NonPublic);
var aggregateSink = (ILogEventSink)aggregateSinkFieldInfo?.GetValue(log);
var sinkEnumerableFieldInfo = aggregateSink?.GetType()
.GetField("_sinks", BindingFlags.Instance | BindingFlags.NonPublic);
var sinks = (ILogEventSink[])sinkEnumerableFieldInfo?
.GetValue(aggregateSink);
if (sinks != null)
{
foreach (var sink in sinks)
{
Console.WriteLine(sink.GetType().FullName);
}
}
This should output:
Serilog.Sinks.SystemConsole.ConsoleSink
Serilog.Sinks.File.FileSink
N.B.: Keep in mind that Serilog wraps sinks in some cases, so you might need to handle that, before you can find the sink you're looking for. For example, if you restrict the minimum level of a sink, your sink will be wrapped into a RestrictedSink
, so you'll have to get a hold of its _sink
field to get the "real" sink you're looking for.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…