Browse Source

Use LogContext to push additional properties.

Instead of creating an `ILogger` for each area, use `LogContext.PushProperty` and also push the type of the source object and its hash.
pull/2498/head
Steven Kirk 8 years ago
parent
commit
9c399429b8
  1. 24
      src/Avalonia.Logging.Serilog/SerilogLogger.cs

24
src/Avalonia.Logging.Serilog/SerilogLogger.cs

@ -1,8 +1,9 @@
// Copyright (c) The Avalonia Project. All rights reserved. // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information. // Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections.Generic; using System;
using Serilog; using Serilog;
using Serilog.Context;
using AvaloniaLogEventLevel = Avalonia.Logging.LogEventLevel; using AvaloniaLogEventLevel = Avalonia.Logging.LogEventLevel;
using SerilogLogEventLevel = Serilog.Events.LogEventLevel; using SerilogLogEventLevel = Serilog.Events.LogEventLevel;
@ -14,7 +15,6 @@ namespace Avalonia.Logging.Serilog
public class SerilogLogger : ILogSink public class SerilogLogger : ILogSink
{ {
private readonly ILogger _output; private readonly ILogger _output;
private readonly Dictionary<string, ILogger> _areas = new Dictionary<string, ILogger>();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SerilogLogger"/> class. /// Initializes a new instance of the <see cref="SerilogLogger"/> class.
@ -36,21 +36,21 @@ namespace Avalonia.Logging.Serilog
/// <inheritdoc/> /// <inheritdoc/>
public void Log( public void Log(
AvaloniaLogEventLevel level, AvaloniaLogEventLevel level,
string area, string area,
object source, object source,
string messageTemplate, string messageTemplate,
params object[] propertyValues) params object[] propertyValues)
{ {
ILogger areaLogger; Contract.Requires<ArgumentNullException>(area != null);
Contract.Requires<ArgumentNullException>(messageTemplate != null);
if (!_areas.TryGetValue(area, out areaLogger)) using (LogContext.PushProperty("Area", area))
using (LogContext.PushProperty("SourceType", source?.GetType()))
using (LogContext.PushProperty("SourceHash", source?.GetHashCode()))
{ {
areaLogger = _output.ForContext("Area", area); _output.Write((SerilogLogEventLevel)level, messageTemplate, propertyValues);
_areas.Add(area, areaLogger);
} }
areaLogger.Write((SerilogLogEventLevel)level, messageTemplate, propertyValues);
} }
} }
} }

Loading…
Cancel
Save