Node.js
Traces | Metrics | App Logs | Custom Logs | Profiling |
---|---|---|---|---|
✅ | ✖ | ✖ | ✅ | ✅ |
This guide walks you through setting up Application Performance Monitoring (APM) on a Node.js application. These instructions can also be found on the Installation page in your Middleware Account. View example code here.
Prerequisites
1 Infra Agent
Infrastructure Agent (Infra Agent). To install the Infra Agent, see our Installation Guide.
2 Node.js Version
Node.js version 18.17.1
or above. Check your Node.js version with the following command:
Bash
node --version
3 Python Version
Python version 3.8
or above. Check your Python version with the following command:
Bash
python3 --version
Install
Step 1: Install Node.js
APM Package
Run the following command in your terminal:
Bash
npm install @middleware.io/node-apm --save
Step 2: Initialize Tracker
Add the following lines to the beginning of your application code base. The access token is your account key, which can be found on the Installation page.
const tracker = require('@middleware.io/node-apm'); tracker.track({ serviceName: "your-service-name", accessToken: "<MW_API_KEY>" });
If you want to track APM data across different deployments of your application. You can pass along the app.version
,
For Example, If your deployment version is 1.2.0
the config should look something like this.
const tracker = require('@middleware.io/node-apm'); tracker.track({ serviceName: "your-service-name", accessToken: "<MW_API_KEY>", customResourceAttributes: { "app.version": "1.2.0", } });
Step 3: Container Variables
Docker
Applications running in a container require an additional environment variable. If your application is not running in a container, move to Step 4.
For Docker containers, add the following environment variable to your application.
Bash
MW_AGENT_SERVICE=<DOCKER_BRIDGE_GATEWAY_ADDRESS>
The DOCKER_BRIDGE_GATEWAY_ADDRESS
is the IP address of the gateway between the Docker host and bridge network. This is 172.17.0.1
by default. Learn more about Docker bridge networking here
Kubernetes
Bash
kubectl get service --all-namespaces | grep mw-service
Then add the following environment variable to your application deployment YAML file.
Bash
MW_AGENT_SERVICE=mw-service.mw-agent-ns.svc.cluster.local
Step 4: Capture Application Data
Traces
Distributed tracing is automatically enabled upon completion of Step 2.
Span Attributes
For any automatically instrumented endpoints, add the following code snippet:
router.post("/email/send", async (req, res) => { const email = req.body.email; tracker.setAttribute("email", email); res.json({ status: "email sent" }); });
Custom Logs
To ingest custom logs into Middleware, utilize the following functions inside your logging method based on desired log severity levels.
index.js
tracker.info('Info sample'); tracker.warn('Warning sample'); tracker.debug('Debugging Sample'); tracker.error('Error Sample');
To add stack traces along with the error log, use the following error tracking function.
index.js
tracker.error(new Error('Error sample with stack trace'));
Custom Metrics and Spans
Create custom instruments and spans by exposing the meter and tracer with the following pattern:
const express = require("express"); const app = express(); const tracker = require("@middleware.io/node-apm"); // Initialize the tracker tracker.track({ // Service name differentiates your applications in the APM section of the Middleware platform. serviceName: "<your_service_name_here>", // You can find your access token in the Middleware platform by going to the installation page. accessToken: "<MW_API_KEY>",
Profiling
Application Profiling is auto-configured upon completing Step 2.
Stack Traces
Use the errorRecord
method to record a stack trace when an error occurs. See an example of this method below.
index.js
app.get('/error', function (req, res) { try{ throw new Error('oh error!'); }catch (e) { track.errorRecord(e) } res.status(500).send("wrong"); });
NestJS Framework [Optional]
Step 1: Install Node Typescript APM
npm install mw-node-apm-ts
Step 2: Import Package in main.ts
Import the following package in your main.ts file:
import { track } from 'mw-node-apm-ts'; async function bootstrap() { track({ serviceName: 'NestJS Test', accessToken: 'your-api-token', }); const app = await NestFactory.create(AppModule, { bufferLogs: true });
Step 3: Capture Application Data
The following is a sample function that fetches a user’s email address and throws an error if the user is not found, while also logging the error using a third-party logging function.
Use the below pattern for any other available methods that are mentioned in Step 4.
import { error } from 'mw-node-apm-ts'; async sampleCode(data: userDto): Promise<IResponse> { const user = await this.userService.getUserByEmail(loginDto.email); if (!user) { error('User not found'); throw new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY,
Continuous Profiling
Continuous profiling captures real-time performance insights from your application to enable rapid identification of resource allocation, bottlenecks, and more. Navigate to the Continuous Profiling section to learn more about using Continuous Profiling with the Node.js APM.
Troubleshooting
node-gyp
Failing/Missing Dependencies
If node-gyp
fails to build or your infrastructure is missing dependencies, run the following command:
Shell
sudo apt-get build-dep build-essential sudo apt-get install gcc sudo apt-get install g++ sudo apt-get install make
Running Apps on Docker
If you are unable to run your Node.js app on Docker, open port 9319
locally to enable proper firewall configurations.
Need assistance or want to learn more about Middleware? Contact our support team in Slack.