gpt4 book ai didi

.net - 如何在 Serilog 中手动呈现模板及其参数?

转载 作者:行者123 更新时间:2023-12-05 03:14:08 25 4
gpt4 key购买 nike

如何实现下面的方法?

string BuildSerilogMessage(string messageTemplate, params object[] propertyValues);

参数与ILogger.Debug等接受的参数相同

我想要这个的原因是因为我想在中间异常中保留模板/值,它也需要有单个字符串消息。它基本上是这样的:

// this exception is designed to be easily loggable by serilog
[Serializable]
public class StructuredException : Exception {
public string MessageTemplate { get; private set; }
public object[] PropertyValues { get; private set; }

public StructuredException(string messageTemplate, params object[] propertyValues)
: base(BuildMessage(messageTemplate, propertyValues))
{
MessageTemplate = messageTemplate;
PropertyValues = propertyValues;
}

public StructuredException(Exception inner, string messageTemplate, params object[] propertyValues)
: base(BuildMessage(messageTemplate, propertyValues), inner)
{
MessageTemplate = messageTemplate;
PropertyValues = propertyValues;
}

private static string BuildMessage(string messageTemplate, object[] propertyValues) {
// ???
}
}

最佳答案

an example in the Akka.NET repo这是完成的,尽管参数中只支持标量值。

基本概念是使用MessageTemplateParser 获取模板:

var parser = new MessageTemplateParser();
var template = parser.Parse(messageTemplate);

然后使用参数从模板中压缩标记:

var properties = template.Tokens
.OfType<PropertyToken>()
.Zip(propertyValues, Tuple.Create)
.ToDictionary(
p => p.Item1.PropertyName,
p => new ScalarValue(p.Item2));

最后渲染:

var rendered = template.Render(properties);

(对于此处可能无法编译的部分,提前致歉。)

关于.net - 如何在 Serilog 中手动呈现模板及其参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875831/

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