如何覆盖 Serilog 在 Guid(或其他内置基元)上使用 ToString?



我使用Serilog来记录一个以Guid作为玩家标识符的多人游戏。

伐木比我喜欢的噪音更大,所以我想把它修剪一下,做一些水槽。通常,人类(即我(只需要Guid的前8位数字来调试问题。我已经为Guid编写了一个名为ShortForm()的扩展方法,我希望Serilog控制台、文件和Slack接收器使用它,而不是完整的Guid。

public static string ShortForm(this Guid guid)
{
if (guid == Guid.Empty) 
return "????????";
return guid.ToString().Substring(0, 8);
}

我尝试在构造函数中使用Destructure.ByTransforming(),但似乎不起作用:

string _outputTemplate = "[{@t:HH:mm:ss} {@l:u3}] {@m}n{@x}";
ExpressionTemplate _consoleExpression = new ExpressionTemplate(_outputTemplate, theme: TemplateTheme.Literate);
Log.Logger = new LoggerConfiguration().
... etc snipped ...
Destructure.ByTransforming<Guid>(g => g.ShortForm()).
WriteTo.Console(formatter: _consoleExpression).
CreateLogger();

在我的代码库中:

//code
Log.Information("{@Guid} disconnected from {IP}", removedGuid, serverEvent.EndPoint); 
//console output
[12:30:54 INF] 00000000-0000-0000-0000-000000000000 disconnected from 127.0.0.1:59548
//or, if authenticated:
[12:34:01 INF] 3babffd8-68cb-41c2-87b6-d2beffbd431b disconnected from 127.0.0.1:51933

有办法做到这一点吗?

我查找了Serilog的存储库,发现Guid被处理为Scalar类型,没有办法使用.Destructure.ByTransforming来转换它https://github.com/serilog/serilog/blob/697a23189e3068bfe0da1460a2676913239d2757/src/Serilog/Capturing/PropertyValueConverter.cs#L45.

但是您可以使用自定义格式化程序将Guid格式化为字符串(https://github.com/serilog/serilog/wiki/Formatting-Output#format-提供商(。

我做了一个小测试-https://gist.github.com/sergey-miryanov/544b8413da70a0be455ac3903c1a781c

最新更新