@tim_deschryver
OpenTelemetry is a part of Cloud Native Computing Foundation (CNCF), and is the standard to monitor your application.
OpenTelemetry makes robust, portable telemetry a built-in feature of cloud-native software.
With the use of Signals, which are traces, logs, and metrics, OpenTelemetry gives you a good insight into the state of the application.This helps you to get a better understanding of the application and can help you to detect problems and possible problems in the future.There are official packages for most of the ecosystems, including one for JavaScript (with TypeScript support) in a Node.js environment and one to use in a browser context, the latter is the one that we'll explore in this blog post.
OpenTelemetry is something I discovered at the end of 2022 and didn't know I needed. It's high up on my list of technologies that I want to explore and know better this year.While there is already useful content surrounding this topic, and the official documentation also provides lots of goodies in the sorts of API documentation, guides, and examples, I might write about my experience with OpenTelemetry in the future.But for frontend applications using TypeScript, I find that there's a lack of information about using OpenTelemetry. That's why I want to already take the time and share how I added OpenTelemetry to an application built with Angular.
In this blog post we learn how to configure the OpenTelemetry SDK to get graphs like the following.
Setup
I followed the "Getting Started" documentation to add OpenTelemetry to my application.This leads to the following bare code, in which some parts are left out but will be covered on later.
The code registers two main essentials:
- instrumentations, which are responsible to create traces for specific events
- processors, which are run to process the data before being sent (with the use of an exporter)
instrument.ts
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
const provider = new WebTracerProvider();
provider.addSpanProcessor(/* TODO */);
provider.register();
registerInstrumentations({
instrumentations: [
/* TODO */
],
});
To follow along with me, install the initial packages that are used in the above snippet:
npm install @opentelemetry/sdk-trace-web @opentelemetry/instrumentation
Creating Traces with Instrumentations
A trace represents a collection of events (spans is the correct term) that are related to each other.It usually starts with an initial event that is invoked by an end user.
Traces give us the big picture of what happens when a request is made by a user or an application.
We can for example create a trace when a button is clicked.But, instead of writing this code manually, I'm using the @opentelemetry/auto-instrumentations-web
package.
@opentelemetry/auto-instrumentations-web
bundles some packages and does most of the heavy lifting for us.It automatically creates traces for most of the important events, this includes:
- user events, e.g. when a button is clicked
- information about the initial page load, e.g. resources that are downloaded and how long it tookHTTP traffic, .e.g. the endpoint that is called with the response status and response time
The
@opentelemetry/auto-instrumentations-web
package can also serve as a solid base to introduce the usefulness of OpenTelemetry to your team.
To start collecting the events add the exported getWebAutoInstrumentations
method to the instrumentations collection.By default, this creates traces for all of the above events, but you can choose to opt out of individual packages.The following example uses the default configuration for all packages.
instrument.ts
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
const provider = new WebTracerProvider();
provider.addSpanProcessor(/* TODO */);
provider.register();
registerInstrumentations({
instrumentations: [
getWebAutoInstrumentations({
// not needed to add the following, but it better shows the intention
'@opentelemetry/instrumentation-document-load': {},
'@opentelemetry/instrumentation-user-interaction': {},
'@opentelemetry/instrumentation-fetch': {},
'@opentelemetry/instrumentation-xml-http-request': {},
}),
],
});
To follow along with me, install the additional packages that are used in the above snippet:
npm install @opentelemetry/auto-instrumentations-web
Depending on the version you need to enable the
skipLibCheck
tsconfig option because the package may contain invalid types.
Sending Traces with Processors and Exporters
Now that the instrumentations are plugged in and are creating traces, we need to start sending them somewhere so they can be useful.You can either send them directly to a backend, or to your hosted collector (recommended).
To send the traces (and later logs and metrics), we use one or more processors (to transform/batch signals) and an exporter (how to send signals).
To give a good overview to see which traces are created and when they're exported, the most simple solution is to log them to the console.But this isn't useful in a production environment, and it also isn't visual and doesn't show you the big picture.
Instead, I encourage you to directly use a solution that is used in a production environment, and which is also capable to analyze the collected telemetry data.This way you also get the hang of how to use your tools that are used in production for when it really matters.Luckily, there is no difference between the signals that are logged to the console and the ones that are sent to a backend/collector.
The good tools also immediately show you the signals that are received without any delay.This means you can see the signals in real time, just like in the console.The big benefit of this is that the signals are aggregated into views and graphs that give you a better overview.They show you when the signal is created, together with its parent and children.
You can spin up your own collector and/or backend, or use a cloud-based solution.When I dove into OpenTelemetry I used Honeycomb, which is used in the next examples.
You can create a free account in the Honeycomb application
To send the traces add a processor and exporter to the web tracer provider.In the following example, the ConsoleSpanExporter
export is used to log the traces, and the OTLPTraceExporter
exporter is used to send them to Honeycomb.
The ConsoleSpanExporter
exporter uses a SimpleSpanProcessor
, while the OTLPTraceExporter
exporter uses the BatchSpanProcessor
processor.The latter batches the traces before handing them to the exporter, while the SimpleSpanProcessor
processor directly forwards the traces.
instrument.ts
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';
const provider = new WebTracerProvider();
// For demo purposes only, immediately log traces to the console
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
// Batch traces before sending them to HoneyComb
provider.addSpanProcessor(
new BatchSpanProcessor(
new OTLPTraceExporter({
url: 'https://api.honeycomb.io/v1/traces',
headers: {
'x-honeycomb-team': 'YOUR_KEY_HERE',
},
}),
),
);
provider.register();
registerInstrumentations({
instrumentations: [
getWebAutoInstrumentations({
'@opentelemetry/instrumentation-document-load': {},
'@opentelemetry/instrumentation-user-interaction': {},
'@opentelemetry/instrumentation-fetch': {},
'@opentelemetry/instrumentation-xml-http-request': {},
}),
],
});
To follow along with me, install the additional packages that are used in the above snippet:
npm install @opentelemetry/exporter-trace-otlp-http
Traces overview
To start instrumenting your Angular application, create a new instrument.ts
file and copy-paste the current state of the snippet into it.
instrument.ts
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';
const provider = new WebTracerProvider();
// For demo purposes only, immediately log traces to the console
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
// Batch traces before sending them to HoneyComb
provider.addSpanProcessor(
new BatchSpanProcessor(
new OTLPTraceExporter({
url: 'https://api.honeycomb.io/v1/traces',
headers: {
'x-honeycomb-team': 'YOUR_KEY_HERE',
},
}),
),
);
provider.register();
registerInstrumentations({
instrumentations: [
getWebAutoInstrumentations({
'@opentelemetry/instrumentation-document-load': {},
'@opentelemetry/instrumentation-user-interaction': {},
'@opentelemetry/instrumentation-fetch': {},
'@opentelemetry/instrumentation-xml-http-request': {},
}),
],
});
Next, import the file into the main.ts
file.
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import './instrument';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});
Now, when you load the application you should see some traces in the console.These traces hold the information about the document load.The traces should also be visible in honeycomb (we'll see how this looks like later).
Let's also add a button to fetch some resources.For this, add the following code to the AppComponent
.
app.component.ts
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button
(click)="btnClick()"
id="my-awesome-button"
class="some-classy-button"
>
Click me
</button>
`,
styles: [],
standalone: true,
})
export class AppComponent {
constructor(private http: HttpClient) {}
btnClick() {
this.http
.get<{id:number, title:string}[]>('https://jsonplaceholder.typicode.com/todos/')
.subscribe((todos) => {
for (const i of (todos).filter((todo) => todo.id <= 10)) {
this.http
.get('https://jsonplaceholder.typicode.com/todos/' + i.id)
.subscribe();
}
});
}
}
Now, when you click the button you should see more traces coming in.The new traces include user interactions (because you clicked the button), and requests (to the JSON placeholder API).
You also see these traces in honeycomb.
When we click a trace to see the details, we can see that the trace contains a lot of information.We can for example, when we open the click event we can see which element is clicked and that the click triggered a fetch request.
We can also see what API endpoint was called, including the response status and response time.
Zone Context
But, there's room for improvement.In the example used in this post, we can see that the click triggers an HTTP request, that actually results in multiple requests.Only the initial request shows up in the graph, and the rest of the requests are not visible.They are however visible as individual traces.
This is because a trace is not aware of the context in which it was created.To fix this, we need to introduce zones.
If you're familiar with zones in Angular this should ring a bell.Within a zone, all underlying traces are aware of the parent.This means that the click event creates a zone, and all the HTTP requests within the zone are grouped in this zone.
Fun fact: it uses Angular's zone.js!
instrument.ts
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 { ZoneContextManager } from '@opentelemetry/context-zone';
const provider = new WebTracerProvider();
// For demo purposes only, immediately log traces to the console
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
// Batch traces before sending them to HoneyComb
provider.addSpanProcessor(
new BatchSpanProcessor(
new OTLPTraceExporter({
url: 'https://api.honeycomb.io/v1/traces',
headers: {
'x-honeycomb-team': 'YOUR_KEY_HERE',
},
}),
),
);
provider.register({
contextManager: new ZoneContextManager(),
});
registerInstrumentations({
instrumentations: [
getWebAutoInstrumentations({
'@opentelemetry/instrumentation-document-load': {},
'@opentelemetry/instrumentation-user-interaction': {},
'@opentelemetry/instrumentation-fetch': {},
'@opentelemetry/instrumentation-xml-http-request': {},
}),
],
});
This results in a trace that includes all the HTTP requests triggered by the click, which looks like this:
Conclusion
That's it!
With the help of the packages provided by OpenTelemetry we can now see what's going on in our Angular application.We didn't have to write custom code to instrument our application, we just had to add a few lines to configure the OpenTelemetry SDK.
In the next posts we'll look at how to make this code more "Angulary", include more information in our traces to make it easier to monitor, how to log errors, and more.
Support me
I appreciate it if you would support me if have you enjoyed this post and found it useful, thankyou in advance.
Support the blogShare on TwitterDiscuss on TwitterEdit on GitHub
FAQs
How do you integrate OpenTelemetry? ›
To start integrating OpenTelemetry into any project, the API is used to define how telemetry is generated. To generate tracing telemetry in your application you will use the OpenTelemetry Trace API from the go.opentelemetry.io/otel/trace package. First, you need to install the necessary packages for the Trace API.
How Angular application can be bootstrapped? ›- Load index. html.
- Load Angular, Other Libraries, and App Code.
- Execute main. ts File.
- Load App-Level Module.
- Load App-Level Component.
- Process Template.
Telemetry data includes logs, metrics, and traces. Angular is a frontend Javascript framework that uses HTML and Typescript. It's a popular framework used by many organizations for their frontend applications.
How to deploy Angular application in IIS? ›- Adding the resource files.
- Create the Application Pool.
- Create the application on the IIS page.
- Enabling the required IIS Windows Features.
- Launch the application at the end of the installation process.
OpenMetrics just standardizes the exposition format through which metrics data must be communicated over a network, whereas OpenTelemetry aims to provide compatibility with OpenMetrics by using this standardized format to export metrics data.
What is difference between OpenTracing and OpenTelemetry? ›OpenTelemetry and OpenTracing are open-source projects used to instrument application code for generating telemetry data. While OpenTelemetry can help you generate logs, metrics, and traces, OpenTracing focuses on generating traces for distributed applications.
Can you explain lazy loading in Angular? ›Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. It improves the speed of the application load time by splitting the application into several bundles. When the user navigates through the app, the bundles are loaded as required.
How do you make an Angular application multilingual? ›- 1) Create an Angular Application.
- 2) Installing ngx-translate package.
- 3) Creating translation files.
- 4) Making required changes in other files.
- 5) Adding a feature to switch between languages.
- Using AoT Compilation. ...
- Using OnPush Change Detection Strategy. ...
- Using Pure Pipes. ...
- Unsubscribe from Observables. ...
- Lazy Loading. ...
- Use trackBy option for For Loop. ...
- Avoid computation in template files. ...
- Usage of Web Workers.
Telemetry is defined as the automatic process of the data created by your systems being remotely collected through the use of agents and protocols. Telemetry data extends to and includes all logs, metrics, events and traces that are created by your applications.
Where is OpenTelemetry used? ›
What is OpenTelemetry used for? OpenTelemetry can be used to solve common issues encountered at organizations running cloud-native applications across distributed systems.
What is telemetry vs observability? ›While observability is concerned with understanding the internal state of a system, and monitoring is concerned with ensuring that a system is working correctly, telemetry is focused on collecting data from remote sources.
What is the best server to deploy Angular app? ›Because these files are static, you can host them on any web server capable of serving files; such as Node.js , Java, .NET, or any backend such as Firebase, Google Cloud, or App Engine.
How to deploy Angular application in production? ›Basic deployment to a remote serverlink
For the simplest deployment, create a production build and copy the output directory to a web server. Copy everything within the output folder ( dist/project-name/ by default) to a folder on the server. Configure the server to redirect requests for missing files to index.html .
- Install Angular CLI.
- Setup Basic Angular Project.
- Create Firebase Account to Deploy Angular Application.
- Install the Firebase Tools using Firebase CLI.
- Login and Initialize Firebase project using Firebase CLI.
- Create Production Build.
- Deploy your Angular App to Firebase Hosting.
Benefits of OpenTelemetry
By giving you a single, universal standard for collecting and sending telemetry data, OpenTelemetry helps you streamline your observability efforts, making it easier for teams to optimize performance and troubleshoot issues.
Most observability vendors provide support for OpenTelemetry data formats. But as it's a huge initiative, we expect it to reach maturity in most signals in the next one to two years."
What are the alternatives to OpenTelemetry? ›Kibana, Grafana, Prometheus, Nagios, and Zabbix are the most popular alternatives and competitors to OpenTelemetry.
Is OpenTelemetry push or pull? ›OpenTelemetry supports two styles of exporter: "push"-based exporters, where the exporter sends data to the backend on a timed interval, and "pull"-based exporters, where the backend will query for the data when it wants it. New Relic is an example of a push-based backend, and Prometheus is a pull-based backend.
Is open telemetry a standard? ›OpenTelemetry is an open source project and unified standard for service instrumentation, or a way of measuring performance.
What is difference between lazy loading and eager loading in Angular? ›
Lazy Loading vs. Eager Loading. While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.
What are the disadvantages of lazy loading in Angular? ›What are the disadvantages of lazy loading? Users may request resources faster than expected: For instance, if a user scrolls quickly down a page, they might have to wait for the images to load. This could negatively impact user experience.
When should you not use lazy loading? ›Make sure that you never Lazy-load any resource required to execute background tasks. For example, it can be a JavaScript component, background image, or other multimedia content. Further, you must not delay the loading for those.
Can an Angular app have multiple modules? ›The root module is the main module in an Angular application. It is generated by the Angular CLI as AppModule and bootstrapped when the application starts. Every other Angular module depends either directly or indirectly on the root module. Only one root module can exist in an Angular application.
Can Angular be used for multi page application? ›Angular is optimized for single-page applications (SPAs), but with a few simple steps it can also be used to display several applications on one page, a "multi-page application", so to speak. Lazy loading and shared code parts are even included!
Can an Angular app have more than one module? ›So now, you need to follow some simple steps to use multiple modules in an Angular application. Create a simple application using Angular CLI. If you are going to use Angular for the first time, click here. I am going to create an application which contains three modules: App, Employee, Admin, Home.
How can I make Angular production faster? ›- Step 1: Update your local environment. First, increase Node's memory limit. ...
- Step 2: Check your build process. ...
- Step 3: Minimize the work required. ...
- Step 4: Upgrade Angular. ...
- Step 5: Use caching. ...
- Step 6: Get help from the professionals.
Protractor. This open-source framework automates end-to-end testing primarily for Angular and AngularJS applications. It works as an integrator of Selenium, WebDriver, Jasmine, NodeJS, and other technologies. That said, Protractor can also work well for regression testing with non-Angular apps.
What is the most efficient to compile in Angular? ›The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser.
How do you collect logs in OpenTelemetry? ›OpenTelemetry recommends to collect application logs using Collector's filelog receiver. Alternatively, another log collection agent, such as FluentBit, can collect logs, then send to OpenTelemetry Collector where the logs can be further processed and enriched.
What are the disadvantages of telemetry system? ›
Demerits/ Disadvantages: The only demerit or limitation of this telemetry system is that it can be used only for short distances because (a) the error due to leakage can become substantial if the length of the wire line is large, and (b) the cost of the line increases directly with its length.
What is diff between monitoring and telemetry? ›Monitoring vs.
Telemetry makes monitoring possible across remote or disparate parts of your IT infrastructure. While many monitoring tools aren't equipped to support cloud-native environments, telemetry offers more robust monitoring capabilities across all tools and applications.
OpenTelemetry is a vendor-agnostic instrumentation library. It provides a set of tools, APIs, and SDKs to create and manage telemetry data(logs, metrics, and traces). Jaeger is an open-source tool focused on distributed tracing of requests in a microservice architecture.
What is the difference between OpenTelemetry API and SDK? ›API allows to construct the Metric of a chosen type. SDK defines the way to query the current value of a Metric to be exported. Every type of a Metric has it's API to record values to be aggregated. API supports both - push and pull model of setting the Metric value.
Where is telemetry data stored? ›The telemetry data has all of the variables in the same packet, so conceptually it could easily be stored in a single database table with a column per variable. The serial number + timestamp would suffice as a key. The size of each telemetry packet is 64 bytes, including the device ID and timestamp.
What are the 3 pillars of observability? ›DevOps teams leverage observability to debug their applications, or troubleshoot the root cause of system issues. Peak visibility is achieved by analyzing the three pillars of observability: Logs, metrics and traces.
What are the two types of telemetry data? ›- Metrics.
- Events.
- Logs.
- Traces.
Benefits of Observability
Observability helps to understand what's going on in production, makes it work better for end users, and eliminates the need for debugging in a Production environment. Monitors the performance of applications. Helps in identifying the root causes of issues and helps in troubleshooting.
This server-side rendering in Angular can help large apps in many different ways, especially to manage a huge number of traffic on the progressive web apps and dynamic web pages. In addition to this, one of the most important benefits of Angular Universal is that it provides a high search engine ranking.
Which is the best backend technology for Angular? ›- Angular [Frontend + JavaScript] ...
- Node. ...
- Django [Frontend + Backend + Python] ...
- Flask [Backend + Python] ...
- Bootstrap [Frontend + CSS] ...
- jQuery [Frontend + JavaScript] ...
- Ruby on Rails [Backend + Ruby] ...
- GraphQL [Backend + JavaScript]
Which backend language is best for Angular? ›
It's a vibrant framework able to build complete client-side applications, and there's so much to do and learn in Angular. Angular 1. x used Javascript, but later releases adopted Typescript, which is a superset of Javascript.
Where to deploy Angular apps? ›command in the root directory of your project. The site will be created in the dist directory and you can deploy that to any web server. This will build the project in the dist directory and this can be pushed to the server. Save this answer.
How do you deploy an application to production? ›- Automate As Much As Possible. ...
- Build and Pack Your Application Only Once. ...
- Deploy the Same Way All the Time. ...
- Deploy Using Feature Flags In Your Application. ...
- Deploy in Small Batches, and Do It Often. ...
- Make Deployments a Mundane Task.
- Choose a prebuilt theme name, or "custom" for a custom theme: You can choose from prebuilt material design themes or set up an extensible custom theme.
- Set up global Angular Material typography styles: ...
- Set up browser animations for Angular Material:
- Method 1: Writing CSS (using Media Queries)
- Method 2: The BreakpointObserver Service.
- Method 3: Writing CSS (without using Media Queries)
- Prerequisites.
- Example Project.
- Running The API.
- Running The Angular UI.
- Project Structure and Development Environment.
- Call The API with HttpClient Module.
- Demo.
- Summary.
OpenTelemetry (also referred to as OTel) is an open-source observability framework made up of a collection of tools, APIs, and SDKs. Otel enables IT teams to instrument, generate, collect, and export telemetry data for analysis and to understand software performance and behavior.
How do you visualize OpenTelemetry metrics? ›...
Presently, OpenTelemetry has specifications for these three signals:
- Logs.
- Metrics and.
- Traces.
OpenTelemetry is a collection of tools, APIs, and SDKs. Use it to instrument, generate, collect, and export telemetry data (metrics, logs, and traces) to help you analyze your software's performance and behavior. OpenTelemetry is generally available across several languages and is suitable for use.
What is the difference between OpenTelemetry SDK and API? ›API allows to construct the Metric of a chosen type. SDK defines the way to query the current value of a Metric to be exported. Every type of a Metric has it's API to record values to be aggregated.
Should I use open telemetry? ›
OpenTelemetry is important because it standardizes the way telemetry data is collected and transmitted to backend platforms. It bridges visibility gaps by providing a common format of instrumentation across all services.
What is the difference between SpanId and TraceId in OpenTelemetry? ›TraceId is used to group all spans for a specific trace together across all processes. SpanId is the identifier for a span.
What are the benefits of OpenTelemetry? ›The primary benefit of OpenTelemetry is that it provides a unified standard for creating and ingesting telemetry data, much like container orchestration standards set years ago by Kubernetes.
What is the difference between Prometheus and OpenTelemetry? ›OpenTelemetry helps you to instrument code to generate telemetry data. In comparison, Prometheus is a metrics monitoring tool. Both Prometheus and OpenTelemetry provide client libraries to instrument your code, but OpenTelemetry client libraries provide a one-stop solution to generate logs, metrics, and traces.
Is OpenTelemetry stable? ›OpenTelemetry Metrics is currently under active development. The data model is stable and released as part of the OTLP protocol.
What is OTLP in OpenTelemetry? ›The OpenTelemetry Protocol (OTLP) specification describes the encoding, transport, and delivery mechanism of telemetry data between telemetry sources, intermediate nodes such as collectors, and telemetry backends.
When should I use SDK over API? ›- An SDK provides a complete development kit for software development for building applications for a specified platform, service, or language.
- An API is used to facilitate communication between two platforms.
Internal APIs, which only internal teams may access. Composite APIs, which combine multiple APIs.