Custom spans
Elastic Cloud Serverless projects are autoscaled environments, fully managed by Elastic and available on Elastic Cloud. Availability This functionality is generally available and ready for production usage. The Elastic Stack includes Elastic's core products such as Elasticsearch, Kibana, Logstash, and Beats. Availability This functionality is generally available and ready for production usage. Unless stated otherwise on the page, this functionality is available when your Elastic Stack is deployed on Elastic Cloud Hosted, Elastic Cloud Enterprise, Elastic Cloud on Kubernetes, and self-managed environments. This documentation corresponds to the latest patch available for each minor version. If you're not using the latest patch, check the release notes for changes. The Elastic APM Node.js agent enables you to trace the execution of operations in your Node.js applications, sending performance metrics and errors to the Elastic APM Server. Availability This functionality is generally available and ready for production usage. This documentation corresponds to the latest patch available for each minor version. If you're not using the latest patch, check the release notes for changes.
Serverless Observability
Generally available
Stack
Generally available
APM Agent Node.js
Generally available
This is an example of how to use custom spans. For general information about the Elastic APM Node.js Span API, see the Span API documentation.
If you want to track and time a custom event that happens in your application during a transaction, you can add a new span to an existing transaction.
In the example below, we create an Express app that times how long it takes to:
- Receive the body of an HTTP POST or PUT request
- Parse JSON sent by the client
var apm = require('elastic-apm-node').start()
var app = require('express')()
// body reader middleware
app.use(function (req, res, next) {
if (req.method !== 'POST' && req.method !== 'PUT') {
return next()
}
// `startSpan` will only return a span if there's an
// active transaction
var span = apm.startSpan('receiving body')
var buffers = []
req.on('data', function (chunk) {
buffers.push(chunk)
})
req.on('end', function () {
req.body = Buffer.concat(buffers).toString()
// end the span after we're done loading data from the
// client
if (span) span.end()
next()
})
})
// JSON parser middleware
app.use(function (req, res, next) {
if (req.headers['content-type'] !== 'application/json') {
return next()
}
// start a span to measure the time it takes to parse
// the JSON
var span = apm.startSpan('parse json')
try {
req.json = JSON.parse(req.body)
} catch (e) {}
// when we've processed the json, stop the custom span
if (span) span.end()
next()
})
// ...your route handler goes here...
app.listen(3000)