Configure elastic-apm-node

elastic cloud latest version

const config = require('./config');
const apm = require('elastic-apm-node').start({
    serviceName: config.ELASTIC_APM_SERVICE_NAME,
    secretToken: config.ELASTIC_APM_SERVICE_SECRET,
    serverUrl:  config.ELASTIC_APM_SERVER_URL,
    environment: config.ELASTIC_APM_ENV,
  })
function globalUser (payload) {
  if (payload.context &&
      payload.context.request &&
      payload.context.request.headers &&
      payload.context.request.headers['x-user-id']) {
    // redact sensitive data
    const xUserId = payload.context.request.headers["x-user-id"]
    console.log(xUserId)
    apm.setUserContext({id: xUserId})
  }
  
  return payload // remember to return the modified payload
}
apm.addFilter(globalUser)
module.exports = apm;

this is not updated user.id

Hi @Supun_Madushanka.

Functions added via apm.addFilter are invoked just before tracing data is sent to the APM server. At this point the span or transaction has already ended, which means that apm.setUserContext(...) -- which is an API to change the active transaction -- will not operate on the payload data in that function.

You said (in your Slack post) that this was an Express app. What will probably work better would be to create a small Express middleware function that does a similar thing. Something like this:

app.use(function (req, res, next) {
  const userId = req.headers['x-user-id']
  if (userId) {
    apm.setUserContext({id: userId})
  }
  next()
})

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.