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 demo project here .
Prerequisites
- Middleware Host Agent (MW Agent), to install the MW Agent please see our installation guide .
- Node.js version 18.17.1 or above. Check your Node.js version with the following command.
node --version
Step 1: Install NPM Package
Run the following command in your terminal.
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({
projectName: "your-project-name",
serviceName: "your-service-name",
accessToken: “<xxxxxxxxxx>”;
});
Step 3: Container Variables
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.
MW_AGENT_SERVICE=<DOCKER_BRIDGE_GATEWAY_ADDRESS>
kubectl get service --all-namespaces | grep mw-service
Then add the following environment variable to your application deployment YAML file.
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.
Custom Logs
To ingest custom logs into Middleware, utilize the following functions inside your logging method based on desired log severity levels.
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.
tracker.error(new Error('Error sample with stack trace'));
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.
app.get('/error', function (req, res) {
try{
throw new Error('oh error!');
}catch (e) {
track.errorRecord(e)
}
res.status(500).send("wrong");
});