gpt4 book ai didi

c# - 在进程之间传递 Serilog LogContext

转载 作者:行者123 更新时间:2023-11-30 23:04:25 24 4
gpt4 key购买 nike

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);
}

一对Clone()Push(ILogEventEnricher enricher)方法看起来很有前途,但如何传递 ILogEventEnricher 的返回实例进程之间?

让我们深入研究 LogContext source code .首先我们看到所有Push变体改变私有(private) Enrichers ImmutableStack<ILogEventEnricher>的属性(property)通过添加 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));
}

Clone()只返回包裹在 SafeAggregateEnricher 中的一堆浓缩剂:

public static ILogEventEnricher Clone()
{
var stack = GetOrCreateEnricherStack();
return new SafeAggregateEnricher(stack);
}

所以我们可以传递 LogContext 的状态通过提取 Clone() 返回的 enricher 中存储的值方法。 ILogEventEnricher有唯一的方法:

public interface ILogEventEnricher
{
void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory);
}

富集剂影响 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)));
}

但是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);
}

现在计划应该很清楚了:

  1. 创建 ILogEventPropertyFactory 的自定义实现收集所有创建的属性。
  2. 克隆LogContext获得聚合浓缩剂。
  3. 调用Enrich在这个最终会调用 CreateProperty 的浓缩器上在我们工厂的每个属性中LogContext .
  4. 序列化收到的属性并在进程之间传递。
  5. 反序列化另一端的属性并填充上下文。

下面是实现这些步骤的代码:

属性值类:

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 类:

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 类:

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 类:

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您可以使用任何您想要的序列化机制。

正如我已经说过的,这个解决方案有其缺点:

  1. 已恢复 LogContext与原始版本不是 100% 相同。原创LogContext可以有不同种类的丰富器,但恢复的上下文将只有 PropertyEnricher 的实例.但是,如果您使用 LogContext,这应该不是问题。作为上面示例中的属性的简单包。

  2. 如果某些上下文增强器直接绕过 propertyFactory 创建属性,则此解决方案将不起作用.

  3. 如果某些附加值的类型无法序列化,则此解决方案将不起作用。 Value楼上PropertyValue类型为 object .您可以将任何类型的属性添加到 LogContext但是您应该有一种方法来序列化它们的数据以在进程之间传递。上面的 JSON 序列化/反序列化适用于简单类型,但如果向 LogContext 添加一些复杂值,则必须对其进行调整。 .

关于c# - 在进程之间传递 Serilog LogContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49423172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com