Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User-configurable synchronized writes #66

Merged
merged 8 commits into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion sample/ConsoleDemo/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,63 @@
using Serilog;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleDemo
{
public class Program
{
public static void Main()
public static void Main(string[] args)
{
if (args != null && args.Length == 1)
{
switch (args[0])
{
case "--sync-root-default":
SystemConsoleSyncTest(syncRootForLogger1: null, syncRootForLogger2: null);
return;
case "--sync-root-separate":
SystemConsoleSyncTest(syncRootForLogger1: new object(), syncRootForLogger2: new object());
return;
case "--sync-root-same":
{
var sameSyncRoot = new object();
SystemConsoleSyncTest(syncRootForLogger1: sameSyncRoot, syncRootForLogger2: sameSyncRoot);
return;
}
}
}

AnsiConsoleThemeTest();
}

static void SystemConsoleSyncTest(object syncRootForLogger1, object syncRootForLogger2)
{
var logger1 = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.WithProperty("Logger", "logger1")
.WriteTo.Console(theme: SystemConsoleTheme.Literate, syncRoot: syncRootForLogger1)
.CreateLogger();

var logger2 = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.WithProperty("Logger", "logger2")
.WriteTo.Console(theme: SystemConsoleTheme.Literate, syncRoot: syncRootForLogger2)
.CreateLogger();

var options = new ParallelOptions { MaxDegreeOfParallelism = 8 };
System.Threading.Tasks.Parallel.For(0, 1000, options, (i, loopState) =>
{
var logger = (i % 2 == 0) ? logger1 : logger2;
logger.Information("Event {Iteration} generated by {ThreadId}", i, Thread.CurrentThread.ManagedThreadId);
});

Log.CloseAndFlush();
}

static void AnsiConsoleThemeTest()
adamchester marked this conversation as resolved.
Show resolved Hide resolved
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
Expand Down
16 changes: 12 additions & 4 deletions src/Serilog.Sinks.Console/ConsoleLoggerConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ public static class ConsoleLoggerConfigurationExtensions
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="outputTemplate">A message template describing the format used to write to the sink.
/// The default is <code>"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"</code>.</param>
/// <param name="syncRoot">An object that will be used to `lock` (sync) access to the console output. If you specify this, you
/// will have the ability to lock on this object, and guarantee that the console sink will not be about to output anything while
/// the lock is held.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
Expand All @@ -52,7 +55,8 @@ public static LoggerConfiguration Console(
IFormatProvider formatProvider = null,
LoggingLevelSwitch levelSwitch = null,
LogEventLevel? standardErrorFromLevel = null,
ConsoleTheme theme = null)
ConsoleTheme theme = null,
object syncRoot = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate));
Expand All @@ -62,7 +66,7 @@ public static LoggerConfiguration Console(
theme ?? SystemConsoleThemes.Literate;

var formatter = new OutputTemplateRenderer(appliedTheme, outputTemplate, formatProvider);
return sinkConfiguration.Sink(new ConsoleSink(appliedTheme, formatter, standardErrorFromLevel), restrictedToMinimumLevel, levelSwitch);
return sinkConfiguration.Sink(new ConsoleSink(appliedTheme, formatter, standardErrorFromLevel, syncRoot), restrictedToMinimumLevel, levelSwitch);
}

/// <summary>
Expand All @@ -71,6 +75,9 @@ public static LoggerConfiguration Console(
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">Controls the rendering of log events into text, for example to log JSON. To
/// control plain text formatting, use the overload that accepts an output template.</param>
/// <param name="syncRoot">An object that will be used to `lock` (sync) access to the console output. If you specify this, you
/// will have the ability to lock on this object, and guarantee that the console sink will not be about to output anything while
/// the lock is held.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
Expand All @@ -82,12 +89,13 @@ public static LoggerConfiguration Console(
ITextFormatter formatter,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
LogEventLevel? standardErrorFromLevel = null)
LogEventLevel? standardErrorFromLevel = null,
object syncRoot = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));

return sinkConfiguration.Sink(new ConsoleSink(ConsoleTheme.None, formatter, standardErrorFromLevel), restrictedToMinimumLevel, levelSwitch);
return sinkConfiguration.Sink(new ConsoleSink(ConsoleTheme.None, formatter, standardErrorFromLevel, syncRoot), restrictedToMinimumLevel, levelSwitch);
}
}
}
13 changes: 12 additions & 1 deletion src/Serilog.Sinks.Console/Sinks/SystemConsole/ConsoleSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ class ConsoleSink : ILogEventSink
readonly LogEventLevel? _standardErrorFromLevel;
readonly ConsoleTheme _theme;
readonly ITextFormatter _formatter;
readonly object _syncRoot = new object();
readonly object _syncRoot;
static readonly object _defaultSyncRoot = new object();

const int DefaultWriteBufferCapacity = 256;

Expand All @@ -41,10 +42,20 @@ public ConsoleSink(
ConsoleTheme theme,
ITextFormatter formatter,
LogEventLevel? standardErrorFromLevel)
: this(theme, formatter, standardErrorFromLevel, _defaultSyncRoot)
{
}

public ConsoleSink(
ConsoleTheme theme,
ITextFormatter formatter,
LogEventLevel? standardErrorFromLevel,
object syncRoot)
adamchester marked this conversation as resolved.
Show resolved Hide resolved
{
_standardErrorFromLevel = standardErrorFromLevel;
_theme = theme ?? throw new ArgumentNullException(nameof(theme));
_formatter = formatter;
_syncRoot = syncRoot ?? _defaultSyncRoot;
}

public void Emit(LogEvent logEvent)
Expand Down