Instrumentation is like adding sensors to your application - it enables you to gather information about how the application is running.It involves adding code to an application to collect data on how it's performing. This data can include things like response times, error rates, and resource utilization. By instrumenting our applications, we can gain insights into how they are behaving in production.
Modern applications are typically instrumented with OpenTelemetry for distributed tracing. Here's a simple example using OpenTelemetry to instrument a Node.js application:
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { ConsoleSpanExporter } = require('@opentelemetry/sdk-trace-node');
const {
getNodeAutoInstrumentations,
} = require('@opentelemetry/auto-instrumentations-node');
const sdk = new NodeSDK({
traceExporter: new ConsoleSpanExporter(),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
This instrumentation will add basic auto-instrumentation with OpenTelemetry onto the application. To further instrument your application, you can create custom spans as such:
import { trace } from "@opentelemetry/api";
const tracer = trace.getTracer('your-custom-traces');
const result = await tracer.startActiveSpan(`business-logic`, async (span) => {
span.setAttributes(args)
// your business logic
const result = await yourBusinessLogic(args)
span.setAttributes(result)
return result
});