在进程之间传递 Serilog LogContext
Passing Serilog LogContext between processes
是否可以在 Serilog
中获取 LogContext
的所有属性? LogContext
是否支持 serialization/deserialization 在进程之间传递上下文?
在进程之间传递 LogContext
状态没有可靠的方法。但是,有一种解决方案适用于大多数情况(答案底部列出了限制)。
LogContext
是一个静态 class 公开了以下方法:
public static class LogContext
{
public static ILogEventEnricher Clone();
public static IDisposable Push(ILogEventEnricher enricher);
public static IDisposable Push(params ILogEventEnricher[] enrichers);
[Obsolete("Please use `LogContext.Push(properties)` instead.")]
public static IDisposable PushProperties(params ILogEventEnricher[] properties);
public static IDisposable PushProperty(string name, object value, bool destructureObjects = false);
}
Clone()
和 Push(ILogEventEnricher enricher)
这对方法看起来很有前途,但是如何在进程之间传递 ILogEventEnricher
的返回实例?
让我们深入探讨 LogContext source code。首先,我们看到所有 Push
变体通过添加 ILogEventEnricher
的新实例来改变 ImmutableStack<ILogEventEnricher>
类型的私有 Enrichers
属性。最常用的方法 PushProperty(string name, object value, bool destructureObjects = false)
添加实例 PropertyEnricher
:
public static IDisposable PushProperty(string name, object value, bool destructureObjects = false)
{
return Push(new PropertyEnricher(name, value, destructureObjects));
}
Clone()
只是返回包裹在 SafeAggregateEnricher
:
中的一堆浓缩物
public static ILogEventEnricher Clone()
{
var stack = GetOrCreateEnricherStack();
return new SafeAggregateEnricher(stack);
}
所以我们可以通过提取 Clone()
方法返回的 enricher 中存储的值来传递 LogContext
的状态。 ILogEventEnricher
有唯一的方法:
public interface ILogEventEnricher
{
void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory);
}
Enrichers 通过将 LogEventPropertyValue
的实例添加到其 Properties
词典中来影响 LogEvent
。不幸的是,没有简单的方法来保存事件 属性 对象的状态,因为 LogEventPropertyValue
是一个抽象的 class,具有 ScalarValue
、DictionaryValue
等后代。
但是我们可以使用 ILogEventPropertyFactory
的自定义实现,它将收集所有创建的属性并将它们公开以在进程之间传输。缺点是不是所有的 enricher 都使用 propertyFactory
。其中一些直接创建属性,例如 ThreadIdEnricher:
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(new LogEventProperty(ThreadIdPropertyName, new ScalarValue(Environment.CurrentManagedThreadId)));
}
然而 PropertyEnricher 这可能是我们案例中最有趣的使用工厂:
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
if (propertyFactory == null) throw new ArgumentNullException(nameof(propertyFactory));
var property = propertyFactory.CreateProperty(_name, _value, _destructureObjects);
logEvent.AddPropertyIfAbsent(property);
}
现在计划应该清楚了:
- 创建收集所有已创建属性的
ILogEventPropertyFactory
的自定义实现。
- 克隆
LogContext
以获得聚合浓缩剂。
- 在这个浓缩器上调用
Enrich
,它最终会在我们的工厂中为 LogContext
中的每个 属性 调用 CreateProperty
。
- 序列化收到的属性并在进程之间传递。
- 反序列化另一端的属性并填充上下文。
下面是实现这些步骤的代码:
属性值class:
public class PropertyValue
{
public string Name { get; set; }
public object Value { get; set; }
public bool DestructureObjects { get; set; }
public PropertyValue(string name, object value, bool destructureObjects)
{
Name = name;
Value = value;
DestructureObjects = destructureObjects;
}
}
LogContextDump class:
public class LogContextDump
{
public ICollection<PropertyValue> Properties { get; set; }
public LogContextDump(IEnumerable<PropertyValue> properties)
{
Properties = new Collection<PropertyValue>(properties.ToList());
}
public IDisposable PopulateLogContext()
{
return LogContext.Push(Properties.Select(p => new PropertyEnricher(p.Name, p.Value, p.DestructureObjects) as ILogEventEnricher).ToArray());
}
}
CaptureLogEventPropertyFactory class:
public class CaptureLogEventPropertyFactory : ILogEventPropertyFactory
{
private readonly List<PropertyValue> values = new List<PropertyValue>();
public LogEventProperty CreateProperty(string name, object value, bool destructureObjects = false)
{
values.Add(new PropertyValue(name, value, destructureObjects));
return new LogEventProperty(name, new ScalarValue(value));
}
public LogContextDump Dump()
{
return new LogContextDump((values as IEnumerable<PropertyValue>).Reverse());
}
}
LogContextSerializer class:
public static class LogContextSerializer
{
public static LogContextDump Serialize()
{
var logContextEnricher = LogContext.Clone();
var captureFactory = new CaptureLogEventPropertyFactory();
logContextEnricher.Enrich(new LogEvent(DateTimeOffset.Now, LogEventLevel.Verbose, null, MessageTemplate.Empty, Enumerable.Empty<LogEventProperty>()), captureFactory);
return captureFactory.Dump();
}
public static IDisposable Deserialize(LogContextDump contextDump)
{
return contextDump.PopulateLogContext();
}
}
用法示例:
string jsonData;
using (LogContext.PushProperty("property1", "SomeValue"))
using (LogContext.PushProperty("property2", 123))
{
var dump = LogContextSerializer.Serialize();
jsonData = JsonConvert.SerializeObject(dump);
}
// Pass jsonData between processes
var restoredDump = JsonConvert.DeserializeObject<LogContextDump>(jsonData);
using (LogContextSerializer.Deserialize(restoredDump))
{
// LogContext is the same as when Clone() was called above
}
我在这里使用 JSON 的序列化,但是对于 LogContextDump
和 PropertyValue
这样的原始类型,您可以使用任何您想要的序列化机制。
正如我已经说过的,这个解决方案有其缺点:
恢复后的LogContext
与原来的不是100%一样。原始 LogContext
可能有不同种类的增强器,但恢复的上下文将只有 PropertyEnricher
的实例。但是,如果您使用 LogContext
作为上述示例中属性的简单包,这应该不是问题。
如果某些上下文增强器直接绕过 propertyFactory
.
创建属性,则此解决方案将不起作用
如果某些附加值的类型无法序列化,则此解决方案将不起作用。 Value
属性 上面 PropertyValue
的类型是 object
。您可以向 LogContext
添加任何类型的属性,但您应该有一种方法来序列化它们的数据以便在进程之间传递。以上 serialization/deserialization 到 JSON 将适用于简单类型,但如果向 LogContext
添加一些复杂值,则必须对其进行调整。
是否可以在 Serilog
中获取 LogContext
的所有属性? LogContext
是否支持 serialization/deserialization 在进程之间传递上下文?
在进程之间传递 LogContext
状态没有可靠的方法。但是,有一种解决方案适用于大多数情况(答案底部列出了限制)。
LogContext
是一个静态 class 公开了以下方法:
public static class LogContext
{
public static ILogEventEnricher Clone();
public static IDisposable Push(ILogEventEnricher enricher);
public static IDisposable Push(params ILogEventEnricher[] enrichers);
[Obsolete("Please use `LogContext.Push(properties)` instead.")]
public static IDisposable PushProperties(params ILogEventEnricher[] properties);
public static IDisposable PushProperty(string name, object value, bool destructureObjects = false);
}
Clone()
和 Push(ILogEventEnricher enricher)
这对方法看起来很有前途,但是如何在进程之间传递 ILogEventEnricher
的返回实例?
让我们深入探讨 LogContext source code。首先,我们看到所有 Push
变体通过添加 ILogEventEnricher
的新实例来改变 ImmutableStack<ILogEventEnricher>
类型的私有 Enrichers
属性。最常用的方法 PushProperty(string name, object value, bool destructureObjects = false)
添加实例 PropertyEnricher
:
public static IDisposable PushProperty(string name, object value, bool destructureObjects = false)
{
return Push(new PropertyEnricher(name, value, destructureObjects));
}
Clone()
只是返回包裹在 SafeAggregateEnricher
:
public static ILogEventEnricher Clone()
{
var stack = GetOrCreateEnricherStack();
return new SafeAggregateEnricher(stack);
}
所以我们可以通过提取 Clone()
方法返回的 enricher 中存储的值来传递 LogContext
的状态。 ILogEventEnricher
有唯一的方法:
public interface ILogEventEnricher
{
void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory);
}
Enrichers 通过将 LogEventPropertyValue
的实例添加到其 Properties
词典中来影响 LogEvent
。不幸的是,没有简单的方法来保存事件 属性 对象的状态,因为 LogEventPropertyValue
是一个抽象的 class,具有 ScalarValue
、DictionaryValue
等后代。
但是我们可以使用 ILogEventPropertyFactory
的自定义实现,它将收集所有创建的属性并将它们公开以在进程之间传输。缺点是不是所有的 enricher 都使用 propertyFactory
。其中一些直接创建属性,例如 ThreadIdEnricher:
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(new LogEventProperty(ThreadIdPropertyName, new ScalarValue(Environment.CurrentManagedThreadId)));
}
然而 PropertyEnricher 这可能是我们案例中最有趣的使用工厂:
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
if (propertyFactory == null) throw new ArgumentNullException(nameof(propertyFactory));
var property = propertyFactory.CreateProperty(_name, _value, _destructureObjects);
logEvent.AddPropertyIfAbsent(property);
}
现在计划应该清楚了:
- 创建收集所有已创建属性的
ILogEventPropertyFactory
的自定义实现。 - 克隆
LogContext
以获得聚合浓缩剂。 - 在这个浓缩器上调用
Enrich
,它最终会在我们的工厂中为LogContext
中的每个 属性 调用CreateProperty
。 - 序列化收到的属性并在进程之间传递。
- 反序列化另一端的属性并填充上下文。
下面是实现这些步骤的代码:
属性值class:
public class PropertyValue
{
public string Name { get; set; }
public object Value { get; set; }
public bool DestructureObjects { get; set; }
public PropertyValue(string name, object value, bool destructureObjects)
{
Name = name;
Value = value;
DestructureObjects = destructureObjects;
}
}
LogContextDump class:
public class LogContextDump
{
public ICollection<PropertyValue> Properties { get; set; }
public LogContextDump(IEnumerable<PropertyValue> properties)
{
Properties = new Collection<PropertyValue>(properties.ToList());
}
public IDisposable PopulateLogContext()
{
return LogContext.Push(Properties.Select(p => new PropertyEnricher(p.Name, p.Value, p.DestructureObjects) as ILogEventEnricher).ToArray());
}
}
CaptureLogEventPropertyFactory class:
public class CaptureLogEventPropertyFactory : ILogEventPropertyFactory
{
private readonly List<PropertyValue> values = new List<PropertyValue>();
public LogEventProperty CreateProperty(string name, object value, bool destructureObjects = false)
{
values.Add(new PropertyValue(name, value, destructureObjects));
return new LogEventProperty(name, new ScalarValue(value));
}
public LogContextDump Dump()
{
return new LogContextDump((values as IEnumerable<PropertyValue>).Reverse());
}
}
LogContextSerializer class:
public static class LogContextSerializer
{
public static LogContextDump Serialize()
{
var logContextEnricher = LogContext.Clone();
var captureFactory = new CaptureLogEventPropertyFactory();
logContextEnricher.Enrich(new LogEvent(DateTimeOffset.Now, LogEventLevel.Verbose, null, MessageTemplate.Empty, Enumerable.Empty<LogEventProperty>()), captureFactory);
return captureFactory.Dump();
}
public static IDisposable Deserialize(LogContextDump contextDump)
{
return contextDump.PopulateLogContext();
}
}
用法示例:
string jsonData;
using (LogContext.PushProperty("property1", "SomeValue"))
using (LogContext.PushProperty("property2", 123))
{
var dump = LogContextSerializer.Serialize();
jsonData = JsonConvert.SerializeObject(dump);
}
// Pass jsonData between processes
var restoredDump = JsonConvert.DeserializeObject<LogContextDump>(jsonData);
using (LogContextSerializer.Deserialize(restoredDump))
{
// LogContext is the same as when Clone() was called above
}
我在这里使用 JSON 的序列化,但是对于 LogContextDump
和 PropertyValue
这样的原始类型,您可以使用任何您想要的序列化机制。
正如我已经说过的,这个解决方案有其缺点:
恢复后的
LogContext
与原来的不是100%一样。原始LogContext
可能有不同种类的增强器,但恢复的上下文将只有PropertyEnricher
的实例。但是,如果您使用LogContext
作为上述示例中属性的简单包,这应该不是问题。如果某些上下文增强器直接绕过
propertyFactory
. 创建属性,则此解决方案将不起作用
如果某些附加值的类型无法序列化,则此解决方案将不起作用。
Value
属性 上面PropertyValue
的类型是object
。您可以向LogContext
添加任何类型的属性,但您应该有一种方法来序列化它们的数据以便在进程之间传递。以上 serialization/deserialization 到 JSON 将适用于简单类型,但如果向LogContext
添加一些复杂值,则必须对其进行调整。