### Basic Fastify Application Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/otel/metrics.md A foundational Fastify application structure. No specific setup is required beyond installing Fastify. ```js 'use strict' const server = require('fastify')({ logger: { level: 'info' } }) server.route({ path: '/', method: 'GET', handler (req, res) { res.send({ hello: 'world' }) } }) server.listen({ port: 8080 }) ``` -------------------------------- ### Install Git via Homebrew Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/developer-setup.md Installs Git using Homebrew. After installation, configure your SSL key/certificate and username. ```bash brew install git ``` -------------------------------- ### Core Instrumentation Configuration Example Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/module-instrumentations.md Example configuration for a core instrumentation module, specifying its type and filename. ```javascript http: { type: MODULE_TYPE.TRANSACTION, file: 'http.js' } ``` -------------------------------- ### Install Node.js Agent Dependencies Source: https://github.com/newrelic/node-newrelic/blob/main/README.md Install the project's dependencies using npm after cloning the repository. ```bash $ npm install ``` -------------------------------- ### Install Node.js via NVM Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/developer-setup.md Installs Node.js version 20 using NVM. You can replace '20' with any other desired version. ```bash nvm install 20 ``` -------------------------------- ### Configure Multiple Application Names Source: https://github.com/newrelic/node-newrelic/blob/main/NEWS.md This example shows how to use the identifier override to uniquely identify agent instances on the same host when they have multiple application names. ```javascript app_name['myName', 'unique1'] app_name['myName', 'unique2'] ``` -------------------------------- ### Install Node Version Manager (NVM) Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/developer-setup.md Installs NVM, a tool for managing multiple Node.js versions. Ensure you check the repository for the latest version number. ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash ``` -------------------------------- ### First Party External Instrumentation Example Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/module-instrumentations.md Configures an external first-party instrumentation by providing the npm package identifier. No module type is needed for external instrumentations. ```javascript 'koa': {module: '@newrelic/koa'} ``` -------------------------------- ### Install New Relic Node.js Agent Source: https://github.com/newrelic/node-newrelic/blob/main/README.md Install the `newrelic` package using npm. This is the first step in instrumenting your Node.js application. ```sh $ npm install newrelic ``` -------------------------------- ### Start a Web Transaction Source: https://github.com/newrelic/node-newrelic/blob/main/Migration Guide.md Use `newrelic.startWebTransaction()` to initiate a web transaction. The callback is invoked immediately and works with promises. ```javascript const newrelic = require('newrelic'); // Example using a callback newrelic.startWebTransaction('my-web-transaction', () => { // Transaction logic here // Call newrelic.endTransaction() when done if not using promises }); // Example with promises newrelic.startWebTransaction('my-promise-transaction', async () => { await someAsyncOperation(); // Transaction will end automatically when the promise resolves }); ``` -------------------------------- ### Install npm 2.0.0 or higher Source: https://github.com/newrelic/node-newrelic/blob/main/Migration Guide.md Use this command to install npm version 2.0.0 or higher if you are using an earlier version of Node.js 0.10. ```sh $ npm install --global npm@2 ``` -------------------------------- ### Basic Shim.wrap Example Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/function-wrapping.md This example demonstrates the most basic usage of shim.wrap to replace the 'helloWorld' method on 'testObject'. The wrapper function returns a new function that logs a custom message, effectively overriding the original method's behavior. ```javascript // our wrappers will go here // ... shim.wrap(testObject, 'helloWorld', function wrapCreator(){ return function wrappedHelloWorld(console) { console.log("I am the new method!"); } }); ``` -------------------------------- ### First Party Internal Instrumentation Example Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/module-instrumentations.md Configures an internal first-party instrumentation by specifying its module type. The agent automatically loads the instrumentation file based on the module name. ```javascript 'express': {type: MODULE_TYPE.WEB_FRAMEWORK} ``` -------------------------------- ### Start a Background Transaction Source: https://github.com/newrelic/node-newrelic/blob/main/Migration Guide.md Use `newrelic.startBackgroundTransaction()` for background tasks. The callback is invoked immediately and supports promises. ```javascript const newrelic = require('newrelic'); // Example using a callback newrelic.startBackgroundTransaction('my-background-task', () => { // Background task logic here // Call newrelic.endTransaction() when done if not using promises }); // Example with promises newrelic.startBackgroundTransaction('my-promise-background-task', async () => { await processQueue(); // Transaction will end automatically when the promise resolves }); ``` -------------------------------- ### Convert .proto to .json using protobufjs-cli Source: https://github.com/newrelic/node-newrelic/blob/main/lib/grpc/endpoints/infinite-tracing/Readme.md Use this command to convert a .proto file to a JSON descriptor file. Ensure protobufjs-cli is installed. ```sh npx --package=protobufjs-cli -c 'pbjs --keep-case v1.proto' > v1.json ``` -------------------------------- ### External Instrumentation Setup Function Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/module-instrumentations.md The export function for external instrumentation modules. It receives a shim object and the module to instrument. ```javascript module.exports = function instrument(shim, moduleToInstrument) { //wrap your methods and do your newrelic-y things here } ``` -------------------------------- ### Enable Prerelease Feature Flag Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/feature-flags.md To enable a prerelease feature flag, add a `feature_flags` property to your agent configuration. This example shows how to enable a hypothetical `example_new_instrumentation` behavior. ```javascript { feature_flag: { example_new_instrumentation: true } } ``` -------------------------------- ### Configure MySQL Docker Container Source: https://github.com/newrelic/node-newrelic/blob/main/docker/Readme.md Example Docker Compose configuration for a MySQL container. Mounts local configuration files and sets up environment variables and health checks. ```yaml mysql: container_name: nr_node_mysql platform: ${DOCKER_PLATFORM:-linux/amd64} image: mysql:8.3 volumes: - "./docker/mysql:/etc/mysql/conf.d" ports: - "3306:3306" environment: MYSQL_ALLOW_EMPTY_PASSWORD: 1 healthcheck: test: ["CMD", "mysql" ,"-h", "mysql", "-P", "3306", "-u", "root", "-e", "SELECT 1"] interval: 1s timeout: 10s retries: 30 ``` -------------------------------- ### Configuring URL Obfuscation with Regex Source: https://github.com/newrelic/node-newrelic/blob/main/NEWS.md Enable and configure URL obfuscation using regular expressions in your New Relic configuration. This example shows how to mask numerical IDs in URLs. ```javascript url_obfuscation: { enabled: true, regex: { pattern: /(\/api\/v1\/users\/)([\[\d\]]+)(\/.*$)/, flags: "i", replacement: '$1**$3' } } ``` -------------------------------- ### Example of Route and Query Parameters in Express Source: https://github.com/newrelic/node-newrelic/blob/main/NEWS.md Illustrates how route and query parameters are captured as attributes on Transactions, Segments, and Spans in an Express.js application. Route parameters are prefixed with `request.parameters.route.*` and query parameters with `request.parameters.*`. ```javascript app.get('/api/users/:id', myMiddleware, myController) ``` ```bash curl http://localhost:3000/api/users/abc123?id=true ``` -------------------------------- ### Bootstrap New Relic ESM Loader Source: https://github.com/newrelic/node-newrelic/blob/main/README.md To use the New Relic Node.js agent with ES Modules, start your program using the `node` command with the `--import` flag pointing to the `esm-loader.mjs` file. This example also includes the `-r newrelic` flag to require the agent. ```sh node --import newrelic/esm-loader.mjs -r newrelic your-program.js ``` -------------------------------- ### Setting up a Test Program for Shim Wrapping Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/function-wrapping.md This script sets up a mock environment to test the Shim.wrap functionality. It manually requires the Shim library and creates a test object with methods to be wrapped. The agent and Shim are mocked to isolate the wrapping logic. ```javascript //File: test.js const newrelic = require('newrelic'); // grab the agent instance from cache and manually // require the shim library -- normally the agent // will handle this for you const agent = require.cache.__NR_cache.agent; const Shim = require('newrelic/lib/shim/shim'); // do the same fnApply/apply shenanigans as the shim library // https://github.com/newrelic/node-newrelic/blob/v7.1.3/lib/shim/shim.js#L17-L19 const fnApply = Function.prototype.apply // create a simple test object that // will stand in for our module const testObject = {}; testObject.helloWorld = function helloWorld(console) { console.log("Hello World! :)"); } testObject.goodbyeWorld = function goodbyeWorld(console) { console.log("Goodbye World! :("); } // create an instance of a Shim, passing in fake // values for the module name and module path, // again, the agent normally takes care of // this for you shim = new Shim(agent, 'fake', '/path/to/fake.js') // our wrappers will go here // ... // call our methods testObject.helloWorld(console); testObject.goodbyeWorld(console); console.log("Done") // exit early to avoid harvest loop process.exit(1) ``` -------------------------------- ### Install Homebrew Package Manager Source: https://github.com/newrelic/node-newrelic/blob/main/documentation/developer-setup.md Installs the Homebrew package manager on macOS. This is a prerequisite for installing other development tools. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` -------------------------------- ### Run All Benchmarks with npm Source: https://github.com/newrelic/node-newrelic/blob/main/test/benchmark/Readme.md Use this command to execute all available benchmark tests via the npm script. ```zsh npm run bench ``` -------------------------------- ### Get Current Transaction Reference Source: https://github.com/newrelic/node-newrelic/blob/main/Migration Guide.md Use `newrelic.getTransaction()` to get a reference to the current transaction. Useful with callback-based consumers or when needing explicit transaction control. ```javascript const newrelic = require('newrelic'); newrelic.startWebTransaction('get-transaction-example', () => { const transaction = newrelic.getTransaction(); console.log('Current transaction:', transaction.name); // Use transaction object for further operations if needed newrelic.endTransaction(); }); ``` -------------------------------- ### Run Benchmarks with New Relic Metrics and .env File Source: https://github.com/newrelic/node-newrelic/blob/main/test/benchmark/Readme.md Execute benchmarks and send metrics to New Relic using an ingest license key specified in a .env file. This method also allows for configuring the metrics host if sending to production instead of staging. ```zsh # Starting at node-newrelic (root directory) cd bin touch .env # Fill out NEW_RELIC_LICENSE_KEY=YOUR_INGEST_LICENSE_KEY # If you are sending metrics to production instead of staging (default), also include: NEW_RELIC_METRICS_HOST=otlp.nr-data.net node --env-file .env ./run-bench.js ```