首页 > 解决方案 > @sentry/node 集成将 bunyan 日志调用包装为面包屑

问题描述

默认情况下,Sentry 具有集成,console.log使其成为面包屑的一部分:

链接:导入名称:Sentry.Integrations.Console

我们如何使它也适用于bunyan logger,例如:

const koa = require('koa');
const app = new koa();
const bunyan = require('bunyan');
const log = bunyan.createLogger({
    name: 'app',
    ..... other settings go here ....
});
const Sentry = require('@sentry/node');
Sentry.init({
    dsn: MY_DSN_HERE,
    integrations: integrations => {
        // should anything be handled here & how?
        return [...integrations];
    },
    release: 'xxxx-xx-xx'
});

app.on('error', (err) => {
    Sentry.captureException(err);
});

// I am trying all to be part of sentry breadcrumbs 
// but only console.log('foo'); is working
console.log('foo');
log.info('bar');
log.warn('baz');
log.debug('any');
log.error('many');  

throw new Error('help!');

PS我已经尝试过bunyan-sentry-stream但没有成功@sentry/node,它只是推送条目而不是将它们视为面包屑。

标签: javascriptnode.jsloggingsentrybunyan

解决方案


Bunyan 支持自定义流,而这些流只是函数调用。见https://github.com/trentm/node-bunyan#streams

下面是一个简单地写入控制台的示例自定义流。直接使用这个例子来代替写入哨兵模块,可能是调用Sentry.addBreadcrumb({})或类似的函数。

请注意,尽管record我下面示例中的变量是 JSON 字符串,因此您可能希望解析它以从中获取日志级别、消息和其他数据以提交给 Sentry。

{
  level: 'debug',
  stream:
    (function () {
      return {
        write: function(record) {
          console.log('Hello: ' + record);
        }
      }
    })()
}

推荐阅读