Ruthvik Deekonda
Ruthvik Deekonda

Reputation: 21

Open Telemetry for react and vanilla JS projects

Can someone help me understand if there is a way to configure open Telemetry on the client side for react and vanilla JS projects all I want to do is to console the traces of fetch call that are being made from the browser.

Most of the documentation I see is only for nodejs. Pls pinpoint a documentation if there are any?

Upvotes: 2

Views: 1200

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20626

The documentation gives a common guide for Javascript. What you do for you React would be same as what you do for Node.js or even simple JS scripts.

Just follow the documentation. Create and export a tracer:

import { ZoneContextManager } from '@opentelemetry/context-zone';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { UserInteractionInstrumentation } from '@opentelemetry/instrumentation-user-interaction';
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';

const setupTracer = () => {
    const provider = new WebTracerProvider();

    provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
    
    provider.register({
      // Changing default contextManager to use ZoneContextManager - supports asynchronous operations - optional
      contextManager: new ZoneContextManager(),
    });
    
    // Registering instrumentations
    registerInstrumentations({
      instrumentations: [
        new DocumentLoadInstrumentation(),
        new UserInteractionInstrumentation(),
        new XMLHttpRequestInstrumentation(),
        new FetchInstrumentation()
      ],
    });
    
}

export default setupTracer;

Import the tracer like this in your app's entry point (usually index.js):

setupTracer();
ReactDOM.render(<App />, document.getElementById('root'));

Upvotes: 1

Related Questions