【问题标题】:How to get user info from Sentry scope when capturing exception or message捕获异常或消息时如何从哨兵范围获取用户信息
【发布时间】:2021-03-04 05:04:06
【问题描述】:

如果我想捕获 Sentry 消息并包含在 Sentry 范围上设置的用户信息,我该怎么做?

例如,如果我将用户 ID 设置为范围

Sentry.configureScope(scope => scope.setUser({ id: '123' }))

然后如果我想发送像"User 123 could not send message 456"这样的哨兵消息

Sentry.captureMessage(`User ${userId} could not send message ${messageId}`)

我可以从周围的代码中获取消息 ID,但是如何访问我在此上下文中在作用域上设置的 user.id

【问题讨论】:

    标签: javascript sentry


    【解决方案1】:

    通过访问Sentry scope,您可以获得user 之类的信息或已配置到Sentry 范围的任何其他信息。

    获取用户 ID 的示例是像这样使用 Sentry local scopes

    Sentry.withScope(scope => {
      const user = scope.getUser()
      Sentry.captureMessage(
        `User ${user.id} could not send message ${messageId}`
      )
    })
    

    但是,这种类型的消息可能会创建很多独特的消息,这可能会产生很多噪音。或许可以考虑另一种方法,其中消息本身可以保持一致且信息丰富,同时将特定于事件的信息添加为 Sentry 上下文或标签。

    例如:

    Sentry.withScope(scope => {
      scope.setTag('messageId', messageId)
      // The user info and user.id is already part of the context in Sentry
      // const user = scope.getUser()
      Sentry.captureMessage(
        `User could not send message`
      )
    })
    

    这样,所有类似的事件都将“堆叠”到 Sentry 中的一个条目中,您可以随时单击它以展开并根据需要按标签搜索等。

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      相关资源
      最近更新 更多