lb777
lb777

Reputation: 73

How to get response from express.js using Sentry?

I use express js for the server and Sentry for logging. In performance monitoring (transaction data), I want to see the data that the server has sent. How do I handle them?

This code does not handle the data in the response.

const server = express();

Sentry.init({...});
server.use(Sentry.Handlers.requestHandler());
server.use(Sentry.Handlers.tracingHandler());

server.use(
  '/api/integration',
  (req, res, next) => {
    return res.status(201).json({
        anyData: 'someData'
    });
  }
);

server.use(Sentry.Handlers.errorHandler());

For example, I want to see the response data on this page https://try.sentry-demo.com/organizations/rich-pegasus/discover/python:5c8cd410244b4732a7094c59859b9d98/?field=title&field=event.type&field=project&field=user.display&field=timestamp&name=All+Events&query=&sort=-timestamp&statsPeriod=24h&yAxis=count%28%29 (this is an example, this is not my page)

I know about res.on('finish', ()=>{}), but it is triggered after the transaction is Sentry completed.

Upvotes: 0

Views: 854

Answers (1)

lb777
lb777

Reputation: 73

This solution helped me

app.use((req, res, next) => {
  const originJson = res.json;
  res.json = (data) => {
    const transactionSentry = Sentry.getCurrentHub()
      .getScope()
      .getTransaction();

    let span = null;

    if (transactionSentry) { 
      span = transactionSentry.startChild();

      span.updateWithContext({
        op: 'middleware',
        description: 'end',
      });

      span.setTag('middleware', 'end');
      span.setData('response', JSON.parse(JSON.stringify(data)));
    }

    if (span)span.finish();
    originJson.call(res, data);
  };
  next();
});

Upvotes: 0

Related Questions