是否可以Serilog
从中获取所有属性LogContext
?是否LogContext
支持序列化/反序列化以在进程之间传递上下文?
没有万无一失的方法可以LogContext
在进程之间传递状态。但是,有一个在大多数情况下都有效的解决方案(限制列在答案底部)。
LogContext
是一个静态类,公开以下方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
和Clone()
方法Push(ILogEventEnricher enricher)
对看起来很有前途,但是如何ILogEventEnricher
在进程之间传递返回的实例呢?
让我们深入研究LogContext 源代码。首先,我们看到所有变体都通过添加新的实例来Push
改变类型Enrichers
的私有属性。最常用的方法添加以下实例:ImmutableStack<ILogEventEnricher>
ILogEventEnricher
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));
}
Run Code Online (Sandbox Code Playgroud)
Clone()
只是返回包裹在以下内容中的丰富器堆栈SafeAggregateEnricher
:
public static ILogEventEnricher Clone()
{
var stack = GetOrCreateEnricherStack();
return new SafeAggregateEnricher(stack);
}
Run Code Online (Sandbox Code Playgroud)
LogContext
因此,我们可以通过提取方法返回的丰富器中存储的值来传递状态Clone()
。ILogEventEnricher
有唯一的方法:
public interface ILogEventEnricher
{
void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory);
}
Run Code Online (Sandbox Code Playgroud)
丰富器通过向其字典中LogEvent
添加 的实例来影响。不幸的是,没有简单的方法来保存事件属性对象的状态,因为它是一个具有 、 等后代的抽象类。LogEventPropertyValue
Properties
LogEventPropertyValue
ScalarValue
DictionaryValue
但是,我们可以使用自定义实现ILogEventPropertyFactory
来收集所有创建的属性并公开它们以在进程之间传输。缺点是并非所有丰富器都使用propertyFactory
. 其中一些直接创建属性,例如ThreadIdEnricher:
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(new LogEventProperty(ThreadIdPropertyName, new ScalarValue(Environment.CurrentManagedThreadId)));
}
Run Code Online (Sandbox Code Playgroud)
然而,对于我们的案例来说, 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);
}
Run Code Online (Sandbox Code Playgroud)
现在计划应该很清楚了:
ILogEventPropertyFactory
创建收集所有创建的属性的自定义实现。LogContext
以获得聚合富集剂。Enrich
这个丰富器,它最终会CreateProperty
为 中的每个属性调用我们的工厂LogContext
。下面是实现这些步骤的代码:
属性值类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
LogContextDump 类:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
CaptureLogEventPropertyFactory 类:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
LogContextSerializer 类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
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
}
Run Code Online (Sandbox Code Playgroud)
我在这里使用了 JSON 序列化,但是对于这样的原始类型,LogContextDump
您PropertyValue
可以使用任何您想要的序列化机制。
正如我已经说过的,这个解决方案有其缺点:
修复后的LogContext
内容与原始版本并不 100% 相同。原始内容LogContext
可能有不同种类的丰富器,但恢复的上下文将只有 的实例PropertyEnricher
。LogContext
但是,如果您将其用作具有上述示例中属性的简单包,那么这应该不是问题。
如果某些上下文丰富器直接绕过创建属性,则此解决方案将不起作用propertyFactory
。
如果某些添加值具有无法序列化的类型,则此解决方案将不起作用。Value
上面的属性PropertyValue
的类型为object
. 您可以添加任何类型的属性,LogContext
但您应该有一种方法来序列化它们的数据以便在进程之间传递。上面的 JSON 序列化/反序列化适用于简单类型,但如果向LogContext
.