Angular OpenTelemetry Instrumentation

This document contains instructions on how to set up OpenTelemetry instrumentation in your Angular applications. OpenTelemetry, also known as OTel for short, is an open source observability framework that can help you generate and collect telemetry data - traces, metrics, and logs from your Nestjs application.

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="<SIGNOZ_ENDPOINT>"
export OTEL_NODE_RESOURCE_DETECTORS="env,host,os"
export OTEL_SERVICE_NAME="<APP_NAME>"
export OTEL_EXPORTER_OTLP_HEADERS="signoz-access-token=<SIGNOZ_ACCESS_TOKEN>"
export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
<your_run_command>
VariableDescription
APP_NAME *Name you want to give to your rust application
SIGNOZ_ENDPOINT *This is ingestion URL which you must have got in mail after registering on SigNoz cloud
SIGNOZ_ACCESS_TOKEN *This is Ingestion Key which you must have got in mail after registering on SigNoz cloud

replace <your_run_command> with the run command of your application

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.

import { registerInstrumentations } from '@opentelemetry/instrumentation';
import {
  WebTracerProvider,
  ConsoleSpanExporter,
  SimpleSpanProcessor,
  BatchSpanProcessor,
} from '@opentelemetry/sdk-trace-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { B3Propagator } from '@opentelemetry/propagator-b3';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const resource = Resource.default().merge(
  new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: '<service_name>',
    [SemanticResourceAttributes.SERVICE_VERSION]: '0.1.0',
  })
);

const provider = new WebTracerProvider({ resource });

provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));

provider.addSpanProcessor(
  new BatchSpanProcessor(
    new OTLPTraceExporter({
      url: 'https://ingest.{REGION}.signoz.cloud:443/v1/traces',
      headers: {
        'signoz-access-token': '{SIGNOZ_INGESTION_KEY}',
      },
    })
  )
);

provider.register({
  propagator: new B3Propagator(),
});

registerInstrumentations({
  instrumentations: [
    getWebAutoInstrumentations({
      '@opentelemetry/instrumentation-document-load': {},
      '@opentelemetry/instrumentation-user-interaction': {},
      '@opentelemetry/instrumentation-fetch': {
        propagateTraceHeaderCorsUrls: /.+/,
      },
      '@opentelemetry/instrumentation-xml-http-request': {
        propagateTraceHeaderCorsUrls: /.+/,
      },
    }),
  ],
});

  • <service_name> : Name of your service.
  • SIGNOZ_INGESTION_KEY : You can find your ingestion key from SigNoz cloud account details sent on your email.

Depending on the choice of your region for SigNoz cloud, the ingest endpoint will vary according to this table.

RegionEndpoint
USingest.us.signoz.cloud:443/v1/traces
INingest.in.signoz.cloud:443/v1/traces
EUingest.eu.signoz.cloud:443/v1/traces

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="<APP_NAME>"
export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
<your_run_command>
VariableDescription
APP_NAME *Name you want to give to your rust application

replace <your_run_command> with the run command of your application

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

import { registerInstrumentations } from '@opentelemetry/instrumentation';
import {
  WebTracerProvider,
  ConsoleSpanExporter,
  SimpleSpanProcessor,
  BatchSpanProcessor,
} from '@opentelemetry/sdk-trace-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { B3Propagator } from '@opentelemetry/propagator-b3';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const resource = Resource.default().merge(
  new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: '<service_name>',
    [SemanticResourceAttributes.SERVICE_VERSION]: '0.1.0',
  })
);

const provider = new WebTracerProvider({ resource });

provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));

provider.addSpanProcessor(
  new BatchSpanProcessor(
    new OTLPTraceExporter({
      url: 'http://localhost:4318/v1/traces',
    })
  )
);

provider.register({
  propagator: new B3Propagator(),
});

registerInstrumentations({
  instrumentations: [
    getWebAutoInstrumentations({
      '@opentelemetry/instrumentation-document-load': {},
      '@opentelemetry/instrumentation-user-interaction': {},
      '@opentelemetry/instrumentation-fetch': {
        propagateTraceHeaderCorsUrls: /.+/,
      },
      '@opentelemetry/instrumentation-xml-http-request': {
        propagateTraceHeaderCorsUrls: /.+/,
      },
    }),
  ],
});
  • <service_name> : Name of your service.

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

import './app/instrument';

Step 5. Run the application

ng serve

Send Traces to SigNoz Self-Host

Instrumenting your Angular App with OpenTelemetry ๐Ÿ› 

Pre-requisites

Enable CORS in the OTel Receiver. Add the below required changes in the otel-collector-config.yaml file which can be generally found here.

      http:
+        cors:
+          allowed_origins:
+            - https://netflix.com  # URL of your Frontend application

Make sure to restart the container after making the config changes

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 Self-Host in this file.

import { registerInstrumentations } from '@opentelemetry/instrumentation';
import {
  WebTracerProvider,
  ConsoleSpanExporter,
  SimpleSpanProcessor,
  BatchSpanProcessor,
} from '@opentelemetry/sdk-trace-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { B3Propagator } from '@opentelemetry/propagator-b3';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const resource = Resource.default().merge(
  new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: '<service_name>',
    [SemanticResourceAttributes.SERVICE_VERSION]: '0.1.0',
  })
);

const provider = new WebTracerProvider({ resource });

provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));

provider.addSpanProcessor(
  new BatchSpanProcessor(
    new OTLPTraceExporter({
      url: 'http://127.0.0.1:4318/v1/traces', //url of OpenTelemetry Collector',
    })
  )
);

provider.register({
  propagator: new B3Propagator(),
});

registerInstrumentations({
  instrumentations: [
    getWebAutoInstrumentations({
      '@opentelemetry/instrumentation-document-load': {},
      '@opentelemetry/instrumentation-user-interaction': {},
      '@opentelemetry/instrumentation-fetch': {
        propagateTraceHeaderCorsUrls: /.+/,
      },
      '@opentelemetry/instrumentation-xml-http-request': {
        propagateTraceHeaderCorsUrls: /.+/,
      },
    }),
  ],
});

Again, http://localhost:4318/v1/traces is the default url for sending your tracing data. We are assuming you have installed SigNoz on your localhost. Based on your environment, you can update it accordingly. It should be in the following format:

http://<IP of SigNoz backend>:4318/v1/traces

NOTE: Remember to allow incoming requests to port 4318 of machine where SigNoz backend is hosted.

Sample Angular App

  • Sample Angular App - contains instrument.ts file with placeholder for URL and Ingestion Details (For SigNoz Cloud)

Best Practices for Configuring OpenTelemetry in Production Angular Environments

When deploying Angular applications instrumented with OpenTelemetry to production, it's crucial to optimize for performance, reliability, and security. Here are some best practices to consider:

  1. Implement Proper Sampling
  • Use intelligent sampling to reduce data volume without losing important information.
  • Consider using a parent-based sampler to maintain consistency across traces.

Example configuration:

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

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

const provider = new WebTracerProvider({
  sampler,
  // other config...
});
  1. Use Batch Processing
  • Implement batch processing to reduce network overhead and improve performance.

Example:

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

const exporter = new OTLPTraceExporter({
  url: 'https://your-collector-endpoint',
});

const provider = new WebTracerProvider();
provider.addSpanProcessor(new BatchSpanProcessor(exporter, {
  maxQueueSize: 100,
  maxExportBatchSize: 10,
  scheduledDelayMillis: 500,
}));
  1. Secure Your Data
  • Use HTTPS for all communication with your collector.
  • Implement proper authentication for your collector endpoints.
  • Be cautious about what data you include in spans, avoiding sensitive information.
  1. Optimize Performance
  • Use async operations where possible to avoid blocking the main thread.
  • Implement custom spans judiciously, focusing on critical paths and operations.

Example of an optimized custom span:

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

async function performCriticalOperation() {
  const span = trace.getTracer('critical-ops').startSpan('criticalOperation');
  try {
    // Perform operation
    const result = await someAsyncOperation();
    span.setAttributes({ 'operation.result': result });
    return result;
  } catch (error) {
    span.recordException(error);
    throw error;
  } finally {
    span.end();
  }
}
  1. Implement Proper Error Handling
  • Ensure all exceptions are properly caught and recorded in spans.
  • Use span events to record important application events.
  1. Use Resource Detection
  • Implement resource detection to automatically capture environment information.

Example:

import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const resource = Resource.default().merge(
  new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'my-angular-app',
    [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
    environment: 'production',
  })
);

const provider = new WebTracerProvider({
  resource: resource,
  // other config...
});
  1. Monitor Your Monitoring
  • Implement health checks for your OpenTelemetry pipeline.
  • Set up alerts for issues with data collection or exporting.

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.

FAQs

The below FAQs are for general trouble shooting for an Angular application:

  1. How does OpenTelemetry differ from other Angular monitoring solutions?

OpenTelemetry stands out due to its vendor-neutral approach and comprehensive coverage of both frontend and backend operations. Unlike some Angular-specific solutions, OpenTelemetry allows for standardized instrumentation across your entire stack.

  1. Can OpenTelemetry impact my Angular app's performance?

While OpenTelemetry does add some overhead, it's designed to be lightweight. With proper configuration and use of sampling techniques, the impact on your application's performance should be minimal.

  1. Is it possible to use OpenTelemetry with existing monitoring tools?

Yes, OpenTelemetry is designed to be compatible with many existing monitoring solutions. You can often export OpenTelemetry data to your current tools, allowing for a gradual transition or hybrid approach.

  1. How can I troubleshoot common OpenTelemetry issues in Angular?

Common issues often relate to context propagation or incorrect configuration. Start by verifying your setup, checking console outputs, and ensuring Zone Context is properly integrated. If problems persist, the OpenTelemetry community forums are an excellent resource for troubleshooting.

The below Frequently Asked Questions (FAQs) are for SigNoz Self-Hosted and Cloud:

  1. How to find what to use in IP of SigNoz if I have installed SigNoz in Kubernetes cluster?

    Based on where you have installed your application and where you have installed SigNoz, you need to find the right value for this. Please use this grid to find the value you should use for IP of SigNoz

  2. I am sending data from my application to SigNoz, but I don't see any events or graphs in the SigNoz dashboard. What should I do?

    This could be because of one of the following reasons:

    1. Your application is generating telemetry data, but not able to connect with SigNoz installation

      Please use this troubleshooting guide to find if your application is able to access SigNoz installation and send data to it.

    2. Your application is not actually generating telemetry data

      Please check if the application is generating telemetry data first. You can use Console Exporter to just print your telemetry data in console first. Join our Slack Community if you need help on how to export your telemetry data in console

    3. Your SigNoz installation is not running or behind a firewall

      Please double check if the pods in SigNoz installation are running fine. docker ps or kubectl get pods -n platform are your friends for this.

What Cloud Endpoint Should I Use?

The primary method for sending data to SigNoz Cloud is through OTLP exporters. You can either send the data directly from your application using the exporters available in SDKs/language agents or send the data to a collector agent, which batches/enriches telemetry and sends it to the Cloud.

My Collector Sends Data to SigNoz Cloud

Using gRPC Exporter

The endpoint should be ingest.{region}.signoz.cloud:443, where {region} should be replaced with in, us, or eu. Note that the exporter endpoint doesn't require a scheme for the gRPC exporter in the collector.

# Sample config with `us` region
exporters:
    otlp:
        endpoint: "ingest.us.signoz.cloud:443"
        tls:
            insecure: false
        headers:
            "signoz-access-token": "<SIGNOZ_INGESTION_KEY>"

Using HTTP Exporter

The endpoint should be https://ingest.{region}.signoz.cloud:443, where {region} should be replaced with in, us, or eu. Note that the endpoint includes the scheme https for the HTTP exporter in the collector.

# Sample config with `us` region
exporters:
    otlphttp:
        endpoint: "https://ingest.us.signoz.cloud:443"
        tls:
            insecure: false
        headers:
            "signoz-access-token": "<SIGNOZ_INGESTION_KEY>"

My Application Sends Data to SigNoz Cloud

The endpoint should be configured either with environment variables or in the SDK setup code.

Using Environment Variables

Using gRPC Exporter

Examples with us region

  • OTEL_EXPORTER_OTLP_PROTOCOL=grpc OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.us.signoz.cloud:443 OTEL_EXPORTER_OTLP_HEADERS=signoz-access-token=<SIGNOZ_INGESTION_KEY>

Using HTTP Exporter

  • OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.us.signoz.cloud:443 OTEL_EXPORTER_OTLP_HEADERS=signoz-access-token=<SIGNOZ_INGESTION_KEY>

Configuring Endpoint in Code

Please refer to the agent documentation.

Sending Data from a Third-Party Service

The endpoint configuration here depends on the export protocol supported by the third-party service. They may support either gRPC, HTTP, or both. Generally, you will need to adjust the host and port. The host address should be ingest.{region}.signoz.cloud:443, where {region} should be replaced with in, us, or eu, and port 443 should be used.

Conclusion

OpenTelemetry is the future for setting up observability for cloud-native apps. It is backed by a huge community and covers a wide variety of technology and frameworks. Using OpenTelemetry, engineering teams can instrument polyglot and distributed applications and be assured about compatibility with a lot of technologies.

In this guide, you have learned how to instrument your Angular application with OpenTelemetry and send telemetry data to SigNoz. Hereโ€™s a quick recap of the steps covered:

  1. Installation of OpenTelemetry Packages: You installed the necessary OpenTelemetry packages to get started.
  2. Configuration: You created the instrument.ts file to configure OpenTelemetry with the appropriate endpoints and settings for sending data to SigNoz.
  3. Implementation: You integrated the instrumentation setup by importing the instrument.ts file into your application's main.ts.
  4. Running the Application: Finally, you ran your Angular application to start collecting and sending telemetry data to SigNoz.

By following these steps, you can monitor and trace your Angular application's performance, gaining valuable insights into its behavior and user interactions.

If you encounter any issues or have any questions, please feel free to reach out for support. Join our Slack community and get assistance from our team and other users in the #support channel.

SigNoz Slack community

Was this page helpful?