
Research
/Security News
Toptal’s GitHub Organization Hijacked: 10 Malicious Packages Published
Threat actors hijacked Toptal’s GitHub org, publishing npm packages with malicious payloads that steal tokens and attempt to wipe victim systems.
@opentelemetry/instrumentation-fetch
Advanced tools
OpenTelemetry instrumentation for fetch http client in web browsers
@opentelemetry/instrumentation-fetch is an npm package that provides automatic instrumentation for the Fetch API, allowing developers to collect telemetry data such as traces and metrics for HTTP requests made using the Fetch API. This is useful for monitoring and debugging web applications.
Automatic Tracing
This feature allows you to automatically trace HTTP requests made using the Fetch API. The code sample demonstrates how to set up the FetchInstrumentation and enable it to start collecting trace data.
const { FetchInstrumentation } = require('@opentelemetry/instrumentation-fetch');
const { NodeTracerProvider } = require('@opentelemetry/node');
const { SimpleSpanProcessor } = require('@opentelemetry/tracing');
const { ConsoleSpanExporter } = require('@opentelemetry/tracing');
const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register();
const fetchInstrumentation = new FetchInstrumentation();
fetchInstrumentation.enable();
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
Custom Attributes
This feature allows you to add custom attributes to the spans created for Fetch API requests. The code sample shows how to set a custom attribute on each span.
const { FetchInstrumentation } = require('@opentelemetry/instrumentation-fetch');
const { NodeTracerProvider } = require('@opentelemetry/node');
const { SimpleSpanProcessor } = require('@opentelemetry/tracing');
const { ConsoleSpanExporter } = require('@opentelemetry/tracing');
const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register();
const fetchInstrumentation = new FetchInstrumentation({
applyCustomAttributesOnSpan: (span, request, response) => {
span.setAttribute('custom-attribute', 'custom-value');
}
});
fetchInstrumentation.enable();
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
Error Handling
This feature allows you to handle errors in Fetch API requests and optionally ignore certain URLs or HTTP methods from being instrumented. The code sample demonstrates how to set up error handling and ignore specific URLs and methods.
const { FetchInstrumentation } = require('@opentelemetry/instrumentation-fetch');
const { NodeTracerProvider } = require('@opentelemetry/node');
const { SimpleSpanProcessor } = require('@opentelemetry/tracing');
const { ConsoleSpanExporter } = require('@opentelemetry/tracing');
const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register();
const fetchInstrumentation = new FetchInstrumentation({
ignoreUrls: [/example\.com/],
ignoreMethods: ['POST']
});
fetchInstrumentation.enable();
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.error('Fetch error:', error));
Axios is a popular HTTP client for making requests from both the browser and Node.js. While it does not provide automatic instrumentation out of the box, it can be integrated with OpenTelemetry using custom instrumentation. Compared to @opentelemetry/instrumentation-fetch, Axios offers more features for making HTTP requests but requires additional setup for telemetry.
Got is another HTTP client for Node.js that is known for its simplicity and performance. Similar to Axios, it does not provide automatic instrumentation but can be integrated with OpenTelemetry through custom instrumentation. Got is often preferred for its lightweight and efficient design compared to @opentelemetry/instrumentation-fetch.
Node-fetch is a lightweight module that brings the Fetch API to Node.js. It is similar to the Fetch API in the browser and can be instrumented using @opentelemetry/instrumentation-fetch. However, node-fetch itself does not provide built-in telemetry capabilities, making it less feature-rich in terms of monitoring compared to @opentelemetry/instrumentation-fetch.
Note: This is an experimental package under active development. New releases may include breaking changes.
This module provides auto instrumentation for web using fetch.
(Note: This instrumentation does not instrument Node.js' fetch. See @opentelemetry/instrumentation-undici
for that.)
npm install --save @opentelemetry/instrumentation-fetch
import {
ConsoleSpanExporter,
SimpleSpanProcessor,
WebTracerProvider,
} from '@opentelemetry/sdk-trace-web';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
const provider = new WebTracerProvider({
spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())]
});
provider.register({
contextManager: new ZoneContextManager(),
});
registerInstrumentations({
instrumentations: [new FetchInstrumentation()],
});
// or plugin can be also initialised separately and then set the tracer provider or meter provider
const fetchInstrumentation = new FetchInstrumentation();
const provider = new WebTracerProvider({
spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())]
});
provider.register({
contextManager: new ZoneContextManager(),
});
fetchInstrumentation.setTracerProvider(provider);
// and some test
fetch('http://localhost:8090/fetch.js');
See examples/tracer-web/fetch for a short example.
Fetch instrumentation plugin has few options available to choose from. You can set the following:
Options | Type | Description |
---|---|---|
applyCustomAttributesOnSpan | FetchCustomAttributeFunction | Function for adding custom attributes |
requestHook | FetchRequestHookFunction | Function for adding custom attributes or headers before the request is handled |
ignoreNetworkEvents | boolean | Disable network events being added as span events (network events are added by default) |
measureRequestSize | boolean | Measure outgoing request length (outgoing request length is not measured by default) |
semconvStabilityOptIn | string | A comma-separated string of tokens as described for OTEL_SEMCONV_STABILITY_OPT_IN in the HTTP semantic convention stability migration guide. See the "Semantic Conventions" section below. |
Up to and including v0.200.0, instrumentation-fetch
generates telemetry using Semantic Conventions v1.7.0.
HTTP semantic conventions (semconv) were stabilized in semconv v1.23.0, and a migration process was defined. instrumentation-fetch
versions 0.201.0 and later include support for migrating to stable HTTP semantic conventions, as described below. The intent is to provide an approximate 6 month time window for users of this instrumentation to migrate to the new HTTP semconv, after which a new minor version will change to use the new semconv by default and drop support for the old semconv. See the HTTP semconv migration plan for OpenTelemetry JS instrumentations.
To select which semconv version(s) is emitted from this instrumentation, use the semconvStabilityOptIn
configuration option. This option works as described for OTEL_SEMCONV_STABILITY_OPT_IN
:
http
: emit the new (stable) v1.23.0 semanticshttp/dup
: emit both the old v1.7.0 and the new (stable) v1.23.0 semanticssemconvStabilityOptIn
includes neither of the above tokens, the old v1.7.0 semconv is used.Span name: With the old v1.7.0 semconv the span name is HTTP {method}
(for example 'HTTP GET'). Using the stable semconv v1.23 for HTTP span names, the span name is {method}
(for example 'GET'). If both semconv versions are being emitted, the old name wins. (This instrumentation does not currently support adding an {http.route}
to the span name.)
Span status: When the stable semconv is selected, the span status is set to ERROR when the response status code is >=400
. When just the old semconv is select, the span status is not set.
Span attributes:
v1.7.0 semconv | v1.23.0 semconv | Notes |
---|---|---|
http.method | http.request.method | HTTP request method. With v1.23.0 semconv http.request.method_original may also be included. |
http.url | url.full | Full HTTP request URL |
http.host | server.address and server.port | The hostname and port of the request URL |
http.status_code | http.response.status_code | HTTP response status code |
http.request_content_length_uncompressed | http.request.body.size | This is only added if measureRequestSize is true . |
http.response_content_length_uncompressed | (not included) | Stable HTTP semconv would use http.response.body.size , but this is an Opt-In attribute, so would require adding a configuration option to this instrumentation to enable. |
http.response_content_length | (not included) | Stable HTTP semconv would use http.response.header.<key> , but this is an Opt-In attribute, so would require adding a configuration option to this instrumentation to enable. |
(no equivalent) | error.type | The response status (as a string), if the response status was >=400 . |
http.user_agent | (not included) | Stable HTTP semconv would use user_agent.original , but this is an Opt-In attribute, so would require adding a configuration option to this instrumentation to enable. |
http.scheme | (not included) | Stable HTTP semconv would use url.scheme , but this is an Opt-In attribute, so would require adding a configuration option to this instrumentation to enable. |
http.status_text | (not included) | This is no longer a documented semantic conventions attribute. |
component | (no replacement) | component was an ancient Span "tag" that was never formalized. |
Apache 2.0 - See LICENSE for more information.
FAQs
OpenTelemetry instrumentation for fetch http client in web browsers
The npm package @opentelemetry/instrumentation-fetch receives a total of 492,608 weekly downloads. As such, @opentelemetry/instrumentation-fetch popularity was classified as popular.
We found that @opentelemetry/instrumentation-fetch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
/Security News
Threat actors hijacked Toptal’s GitHub org, publishing npm packages with malicious payloads that steal tokens and attempt to wipe victim systems.
Research
/Security News
Socket researchers investigate 4 malicious npm and PyPI packages with 56,000+ downloads that install surveillance malware.
Security News
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.