如何在新的 @sentry/node API 中包含标签?

How do I include tags in the new @sentry/node API?

在'@sentry/node'发布之前,我使用的是raven模块。在我的所有错误中包含标签就像在配置 Raven 时在选项对象中包含标签 属性 一样简单。

Raven.config(DSN, {
  tags: {...}
})

使用新 API 时如何包含标签?到目前为止我已经尝试过:

Sentry.init({
    dsn: DSN,
    tags: {
        process_name: 'webserver',
    },
})

Sentry.configureScope(scope => {
    scope.setTag('process_name', 'webserver')
})

但两种尝试均无效。

您必须使用 Sentry.configureScope,但如 sdk docs Note that these functions will not perform any action before you have called init() 中所述。

这应该可以,否则你必须联系哨兵:

const Sentry = require('@sentry/node');

Sentry.init({
  dsn: '__DSN__',
  // ...
});

Sentry.configureScope(scope => {
  scope.setExtra('battery', 0.7);
  scope.setTag('user_mode', 'admin');
  scope.setUser({ id: '4711' });
  // scope.clear();
});

根据docs

您可以使用 Sentry.configureScope 配置 Sentry 实例的范围,包括标签。

Sentry.configureScope((scope) => {
  scope.setTag("my-tag", "my value");
  scope.setUser({
    id: 42,
    email: "john.doe@example.com"
  });
});

或者如果您只想发送一个特定事件的数据,您可以使用 Sentry.withScope

Sentry.withScope(scope => {
  scope.setTag("my-tag", "my value");
  scope.setLevel('warning');
  // will be tagged with my-tag="my value"
  Sentry.captureException(new Error('my error'));
});

// will not be tagged with my-tag
Sentry.captureException(new Error('my other error'));