Angular OpenTelemetry Instrumentation

This document contains instructions on how to set up OpenTelemetry instrumentation in your Angular applications and view your application traces in SigNoz.

Send traces to SigNoz Cloud

Based on your application environment, you can choose the setup below to send traces to SigNoz Cloud.

From VMs, there are two ways to send data to SigNoz Cloud.

Step 1. Install OpenTelemetry packages

npm install --save @opentelemetry/api
npm install --save @opentelemetry/auto-instrumentations-node

Step 2. Run the application

export OTEL_TRACES_EXPORTER="otlp"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.<region>.signoz.cloud:443"
export OTEL_NODE_RESOURCE_DETECTORS="env,host,os"
export OTEL_SERVICE_NAME="<service_name>"
export OTEL_EXPORTER_OTLP_HEADERS="signoz-ingestion-key=<your-ingestion-key>"
export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
<your_run_command>
  • <your_run_command>Β is your run command.
  • Set the <region> to match your SigNoz Cloud region
  • Replace <your-ingestion-key> with your SigNoz ingestion key
  • <service_name> is name of your service

Send traces directly to SigNoz Cloud - Code Level Automatic Instrumentation

Step 1. Install OpenTelemetry packages

npm install --save @opentelemetry/sdk-trace-web@^1.21.0                                                                   
npm install --save @opentelemetry/instrumentation@^0.48.0
npm install --save @opentelemetry/auto-instrumentations-web@^0.36.0
npm install --save @opentelemetry/exporter-trace-otlp-http@^0.48.0
npm install --save @opentelemetry/resources@^1.21.0
npm install --save @opentelemetry/propagator-b3@^1.21.0
npm install --save @opentelemetry/semantic-conventions@^1.21.0

Step 2. Create instrument.ts file
You need to configure the endpoint for SigNoz cloud in this file.

instrumentation.ts
import * as opentelemetry from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const sdk = new opentelemetry.NodeSDK({
  traceExporter: new OTLPTraceExporter({
    // optional - default url is http://localhost:4318/v1/traces
    url: 'https://ingest.<region>.signoz.cloud:443/v1/traces', // url is optional and can be omitted 
      headers: {
        "signoz-access-token": "<your-ingestion-key>"
      } // an optional object containing custom headers to be sent with each request
  }),
  instrumentations: [getNodeAutoInstrumentations()],
  resource:  resourceFromAttributes({
    // highlight-next-line
    [SemanticResourceAttributes.service_name]: '<service_name>'
  })
});
sdk.start();
  • Set the <region> to match your SigNoz Cloud region
  • Replace <your-ingestion-key> with your SigNoz ingestion key
  • <service_name> is name of your service

Step 3. Add the below import to your main.ts file.

import './app/instrument';

Step 4. Run the application

ng serve

The data captured with OpenTelemetry from your application should start showing on the SigNoz Traces Explorer.


Send traces via OTel Collector binary - No Code Automatic Instrumentation

OTel Collector binary helps to collect logs, hostmetrics, resource and infra attributes. It is recommended to install Otel Collector binary to collect and send traces to SigNoz cloud. You can correlate signals and have rich contextual data through this way.

πŸ“ Note

You can find instructions to install OTel Collector binary here in your VM. Once you are done setting up your OTel Collector binary, you can follow the below steps for instrumenting your Javascript application.

Step 1. Install OpenTelemetry packages

npm install --save @opentelemetry/api
npm install --save @opentelemetry/auto-instrumentations-node

Step 2. Run the application

export OTEL_TRACES_EXPORTER="otlp"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318/v1/traces"
export OTEL_NODE_RESOURCE_DETECTORS="env,host,os"
export OTEL_SERVICE_NAME="<service_name>"
export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
<your_run_command>
  • <your_run_command>Β is your run command.
  • <service_name> is name of your service

Send traces via OTel Collector binary - Code Level Automatic Instrumentation

Step 1. Install OpenTelemetry Collector binary

OTel Collector binary helps to collect logs, hostmetrics, resource and infra attributes. It is recommended to install Otel Collector binary to collect and send traces to SigNoz cloud. You can correlate signals and have rich contextual data through this way.

You can find instructions to install OTel Collector binary here in your VM.

While creating the config.yaml during the installation fo the OTel Collector Binary, you need to enable CORS under the receivers section of the config file. This is needed so that you don't get CORS error which can hinder sending your Traces to SigNoz Cloud. See the code snippet below to understand how you can enable CORS in your config file:

      http:
+        cors:
+          allowed_origins:
+            - <Frontend-application-URL>  # URL of your Frontend application. Example -> http://localhost:4200, https://netflix.com etc.

<Frontend-application-URL> - URL where your frontend application is running. For Example, http://localhost:4200 or https://netflix.com etc.

NOTE: Make sure to restart your collector after making the config changes

Step 2. Install OpenTelemetry packages

npm install --save @opentelemetry/sdk-trace-web@^1.21.0                                                                   
npm install --save @opentelemetry/instrumentation@^0.48.0
npm install --save @opentelemetry/auto-instrumentations-web@^0.36.0
npm install --save @opentelemetry/exporter-trace-otlp-http@^0.48.0
npm install --save @opentelemetry/resources@^1.21.0
npm install --save @opentelemetry/propagator-b3@^1.21.0
npm install --save @opentelemetry/semantic-conventions@^1.21.0

Step 3. Create instrument.ts file

instrumentation.ts
import * as opentelemetry from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const sdk = new opentelemetry.NodeSDK({
  traceExporter: new OTLPTraceExporter({
    // optional - default url is http://localhost:4318/v1/traces
    url: 'http://localhost:4318/v1/traces', // url is optional and can be omitted 
  }),
  instrumentations: [getNodeAutoInstrumentations()],
  resource:  resourceFromAttributes({
    // highlight-next-line
    [SemanticResourceAttributes.service_name]: '<service_name>'
  })
});
sdk.start();

  • <service_name> is name of your service

Step 4. Add the below import to your main.ts file.

//main.ts
import './app/instrument';

Step 5. Run the application

ng serve

Troubleshooting

When implementing OpenTelemetry in Angular applications, you may encounter several challenges. Here are some common issues and their solutions:

  1. Context Propagation Issues

Challenge: Traces not connecting properly across different services or components.

Solution:

  • Ensure that the W3CTraceContextPropagator is properly configured in your app.module.ts.
  • Use the @opentelemetry/context-zone package to manage context in Angular's Zone.js.

Example configuration:

import { W3CTraceContextPropagator } from '@opentelemetry/core';
import { ZoneContextManager } from '@opentelemetry/context-zone';

// In your OpenTelemetry configuration
const provider = new WebTracerProvider({
  // ... other config
});

provider.register({
  propagator: new W3CTraceContextPropagator(),
  contextManager: new ZoneContextManager()
});
  1. Performance Overhead

Challenge: Noticeable performance degradation after implementing OpenTelemetry.

Solution:

  • Use sampling to reduce the volume of telemetry data.
  • Optimize your instrumentation by focusing on critical paths.

Example of configuring a sampler:

import { ParentBasedSampler, TraceIdRatioBasedSampler } from '@opentelemetry/core';

const sampler = new ParentBasedSampler({
  root: new TraceIdRatioBasedSampler(0.5), // Sample 50% of traces
});

const provider = new WebTracerProvider({
  sampler,
  // ... other config
});
  1. Asynchronous Operations Not Being Traced

Challenge: Traces not capturing asynchronous operations correctly.

Solution:

  • Ensure that Zone.js is properly integrated with OpenTelemetry.
  • Manually create spans for complex asynchronous operations.

Example of manually creating a span:

import { trace } from '@opentelemetry/api';

async function complexOperation() {
  const span = trace.getTracer('my-tracer').startSpan('complexOperation');
  try {
    // Perform async operation
    await someAsyncTask();
    span.end();
  } catch (error) {
    span.recordException(error);
    span.end();
    throw error;
  }
}
  1. Incorrect Configuration of Exporters

Challenge: Telemetry data not reaching the backend (e.g., SigNoz).

Solution:

  • Double-check the exporter configuration, especially the endpoint URLs.
  • Ensure that CORS is properly configured if your collector is on a different domain.

Example of configuring the OTLPTraceExporter:

import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';

const exporter = new OTLPTraceExporter({
  url: 'http://your-collector-url:4318/v1/traces', // Adjust this URL
});

const provider = new WebTracerProvider();
provider.addSpanProcessor(new BatchSpanProcessor(exporter));
  1. Handling Third-Party Libraries

Challenge: Difficulty in tracing operations within third-party libraries.

Solution:

  • Use auto-instrumentation packages when available.
  • For libraries without auto-instrumentation, wrap their methods with custom spans.

Example of wrapping a third-party library method:

import { trace } from '@opentelemetry/api';

function wrapThirdPartyMethod(originalMethod) {
  return function(...args) {
    const span = trace.getTracer('my-tracer').startSpan('thirdPartyOperation');
    try {
      const result = originalMethod.apply(this, args);
      span.end();
      return result;
    } catch (error) {
      span.recordException(error);
      span.end();
      throw error;
    }
  }
}

// Usage
thirdPartyLibrary.someMethod = wrapThirdPartyMethod(thirdPartyLibrary.someMethod);

By being aware of these common challenges and their solutions, you can more effectively implement and troubleshoot OpenTelemetry in your Angular applications.

Was this page helpful?