【问题标题】:How can I add a complete object to Serilog Azure Tablestorage sink, which is not written out in the message?如何将完整的对象添加到 Serilog Azure 表存储接收器,而消息中没有写出?
【发布时间】:2019-09-01 06:59:33
【问题描述】:

所以,我目前正在尝试将 Serilog 包含在我的应用程序中,并且想知道以下问题:

是否可以添加一个对象,以便我的 Azure Tablestorage 接收器将其拾取并将其完全写入相应“数据”列中的 JSON,而不将其添加到纯文本消息中?

我最初的做法是这样的:

m_logger.Information("{message} @{context}", message, context);

这就是我的问题的来源。这行得通,但我想让消息本身保持可读性,并将上下文中的元数据保存在单独的列中。

所以,我的第二次尝试现在看起来像这样:

using (LogContext.PushProperty("context", context))
{
    m_logger.Information("{message}", message);
}

鉴于,我将此添加到我的记录器配置中:.Enrich.FromLogContext()

现在这种工作方式,对象不再出现在消息中,实际上已添加到数据中,但不是将其完全写入 JSON,而是我在 Tablestorage 上的数据列中最终得到的端点:

{"Timestamp":"2019-09-01T08:52:29.4835746+02:00","Level":"Information","MessageTemplate":"{message}","Properties":{"message":"Login happened","context":"MooMed.Core.DataTypes.Session.Context"}}

所以,这似乎只是在内部调用.ToString()

我现在想知道是否有内置的方法来递归地 jsonify 对象,或者我是否必须(似乎)在我的 Context 类中覆盖 .ToString()

【问题讨论】:

    标签: c# azure-table-storage serilog


    【解决方案1】:

    除非您明确告诉 Serilog 解构您的上下文数据,否则它将仅使用 ToString 表示。在您最初的方法中,您告诉 Serilog 通过使用 @ 符号进行解构(尽管我假设您在花括号内而不是在外面使用它,即 {@context} 而不是 @{context} 否则这不应该工作) .

    当使用LogContext 时,您可以告诉 Serilog 在合并属性时通过传递标志来解构对象:

    using (LogContext.PushProperty("context", context, destructureObjects: true))
    {
        // ...
    }
    

    我假设您知道这会将上下文添加到记录在using 块内的所有消息中,包括在调用堆栈下方发生的任何消息。作为替代方案,如果您想更好地控制上下文被添加到哪些消息,您还可以创建一个包含此上下文数据的临时记录器。这是使用ILogger.ForContext 方法完成的:

    var enrichedLogger = m_logger.ForContext("context", context, destructureObjects: true);
    
    // Use `enrichedLogger` instead of `m_logger` whenever you want context data included.
    enrichedLogger.Information("This message has context data attached!");
    m_logger.Information("This message does not have context data attached.");
    

    您也可以使用上述相同的方法为单个消息添加上下文:

    m_logger.ForContext("context", context, destructureObjects: true)
        .Information("This message has context data attached!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多