gpt4 book ai didi

C# 串行日志 : how to log with String interpolation and keep argument names in message templates?

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

如何替换此代码:

string name = "John";
logger.Information("length of name '{name}' is {nameLength}", name, name.Length);

像这样或类似的 C# 字符串插值
string name = "John";
// :-( lost benefit of structured logging: property names not passed to logger
logger.Information($"length of name '{name}' is {name.Length}");

但保持结构化日志的属性名称工作?

好处是:
  • 提高可读性
  • 您永远不会忘记参数列表中的参数或消息模板中的属性名称,尤其是当您更改日志记录代码时
  • 您总是知道此属性名称将打印到您的日志
  • 最佳答案

    Add this file到您的项目。它有 ILogger扩展方法 VerboseInterpolated() , DebugInterpolated()等等。还有unit tests here .

    与格式字符串一起使用

    string name = "John";
    // add 'Interpolated' to method name: InformationInterpolated() instead of Information()
    // add name of the property after the expression. Name is passed to the logger
    logger.InformationInterpolated($"length of name '{name:name}' is {name.Length:Length}");

    但要小心 : 使用错误的方法太容易了。如果不小心使用了 Serilog 的方法,例如 logger.Debug($"length = {length:propertyNameForLogger}") ,它会记录 length = propertyNameForLogger ,因此不会记录任何参数值。这是由于 propertyNameForLogger是您的值(value)的格式。

    匿名类型的使用
    string name = "John";
    // add 'Interpolated' to method name: InformationInterpolated() instead of Information()
    // create an anonymous object with 'new { propertyName }'.
    // It's much slower because of using Reflection, but allows to write the variable name only once.
    logger.InformationInterpolated($"length of name '{new { name }}' is {new { name.Length }}");
    // you can also specify other property names
    logger.InformationInterpolated($"length of name '{new { userName = name }}' is {new { lengthOfName = name.Length }}");

    关于C# 串行日志 : how to log with String interpolation and keep argument names in message templates?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61816775/

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