簡體   English   中英

如何覆蓋 Serilog 在 Guid(或其他內置原語)上使用 ToString?

[英]How can I override Serilog's use of ToString on Guid (or other built-in primitives)?

我正在使用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 作為標量類型處理,沒有辦法使用.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-providers )。

我做了一個小測試 - https://gist.github.com/sergey-miryanov/544b8413da70a0be455ac3903c1a781c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM