Skip to content

Instantly share code, notes, and snippets.

@nblumhardt
Created August 28, 2019 08:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nblumhardt/34c0c273c383da9745f4e974f12b9cac to your computer and use it in GitHub Desktop.
Save nblumhardt/34c0c273c383da9745f4e974f12b9cac to your computer and use it in GitHub Desktop.
Serilog delayed sink initialization example
using System;
using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
class Program
{
static void Main(string[] args)
{
var signalRSink = new LateInitSink();
Log.Logger = new LoggerConfiguration()
.WriteTo.Sink(signalRSink)
.CreateLogger();
Log.Information("Sadly, nobody will get this");
// ... resolve that hub ...
signalRSink.Init(wt => wt.Console());
Log.Information("Ah so nice to be loggin' again");
}
}
class LateInitSink : ILogEventSink, IDisposable
{
// A lot could obviously be done to improve concurrency in this one :-)
readonly object _mutex = new object();
ILogEventSink _sink;
public void Init(Action<LoggerSinkConfiguration> initSink)
{
ILogEventSink inner = null;
LoggerSinkConfiguration.Wrap(
new LoggerConfiguration().WriteTo,
sink => inner = sink,
initSink);
if (inner == null)
throw new InvalidOperationException("Sink not initialized.");
lock (_mutex)
{
if (_sink != null)
throw new InvalidOperationException("Sink already initialized.");
_sink = inner;
}
}
public void Emit(LogEvent logEvent)
{
lock (_mutex)
_sink?.Emit(logEvent);
}
public void Dispose()
{
lock (_mutex)
(_sink as IDisposable)?.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment