Created
August 28, 2019 08:53
-
-
Save nblumhardt/34c0c273c383da9745f4e974f12b9cac to your computer and use it in GitHub Desktop.
Serilog delayed sink initialization example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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