Serilog ForContext 和自定义属性 [英] Serilog ForContext and Custom Properties

查看:103
本文介绍了Serilog ForContext 和自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 Serilog 添加动态自定义属性,但我不确定如何按照我想要的方式进行.代码如下:

I am trying to add dynamic custom properties to Serilog, but I am not sure how to do it the way I want. Here is the code:

    if (data.Exception != null)
        {
            _logger.ForContext("Exception", data.Exception, true);
        }

        await Task.Run(() =>
                _logger.ForContext("User", _loggedUser.Id)
                .Information(ControllerActionsFormat.RequestId_ExecutedAction, data.RequestId, data.ActionName)
            );

但是 Exception 属性没有被持久化.我试过了:

but the Exception property is not being persisted. I have tried:

            await Task.Run(() =>
            _logger.ForContext("Exception", data.Exception, true)
                .ForContext("User", _loggedUser.Id)
                .Information(ControllerActionsFormat.RequestId_ExecutedAction, data.RequestId, data.ActionName)
            );

它工作正常,但有时我必须先处理数据才能使用它(例如迭代包含方法参数的字典).我对想法持开放态度.

and it works fine, but sometimes I have to treat the data before I can use it (like iterating a dictionary containing a method's parameters). I am open to ideas.

推荐答案

您在第一个示例中缺少的是跟踪从 ForContext() 返回的记录器.@BrianMacKay 的示例是执行此操作的一种方法,但您也可以像这样就地执行此操作:

What you're missing in your first example is keeping track of the logger returned from ForContext(). @BrianMacKay's example is one way to do this, but you can also do it in place like so:

var logger = _logger;

if (data.Exception != null)
{
   logger = logger.ForContext("Exception", data.Exception, true);
}

await Task.Run(() =>
    logger.ForContext("User", _loggedUser.Id)
          .Information(ControllerActionsFormat.RequestId_ExecutedAction,
                       data.RequestId, data.ActionName));

这篇关于Serilog ForContext 和自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆