### Run Plugin Tests for amqplib Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Example commands to set up and run tests for the amqplib plugin. This involves starting specific Docker services and running yarn services and yarn test:plugins with appropriate environment variables. ```sh docker compose up -d rabbitmq yarn services yarn test:plugins ``` -------------------------------- ### Install Sirun Source: https://github.com/datadog/dd-trace-js/blob/master/benchmark/sirun/README.md Installs the sirun tool from its Git repository. Ensure you have Rust and Cargo installed. ```sh cargo install --git https://github.com/DataDog/sirun.git --branch main ``` -------------------------------- ### Configuration Metadata Example Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md A minimal JSON example illustrating an entry in `supported-configurations.json`. This defines metadata for a tracer configuration, including its environment variable name, type, default value, and programmatic option mapping. ```json { "DD_AGENT_HOST": [ { "implementation": "E", "type": "string", "configurationNames": ["hostname"], "default": "127.0.0.1", "aliases": ["DD_TRACE_AGENT_HOSTNAME"] } ] } ``` -------------------------------- ### Install Latest dd-trace Source: https://github.com/datadog/dd-trace-js/blob/master/README.md Use these commands to install the latest version of dd-trace for new projects. This is the recommended approach. ```sh $ npm install dd-trace ``` ```sh $ yarn add dd-trace ``` -------------------------------- ### Install Yarn 1.x Globally Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Command to install Yarn version 1.x globally using npm. ```bash npm install -g yarn ``` -------------------------------- ### Boolean Configuration Example Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Demonstrates how to enable runtime metrics using boolean true. This can be set via environment variables or directly in the tracer initialization. ```json "DD_RUNTIME_METRICS_ENABLED": [ { "type": "boolean", "configurationNames": ["runtimeMetrics.enabled", "runtimeMetrics"], "default": "false" } ] ``` ```javascript tracer.init({ runtimeMetrics: true }) ``` ```javascript tracer.init({ runtimeMetrics: { enabled: true } }) ``` ```javascript config.runtimeMetrics.enabled === true ``` -------------------------------- ### Creating a New Plugin Test Directory Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Illustrates the directory creation and initial file setup for testing a new plugin, referencing existing plugin tests for structure. ```bash mkdir -p packages/datadog-plugin-/test cp packages/datadog-plugin-kafkajs/test/index.spec.js packages/datadog-plugin-/test ``` -------------------------------- ### Organize Imports in JavaScript Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Example demonstrating the recommended order for organizing Node.js, third-party, and internal imports. ```javascript const fs = require('node:fs') const path = require('node:path') const express = require('express') const lodash = require('lodash') const { myConf } = require('./config') const { foo } = require('./helper') const log = require('../log') ``` -------------------------------- ### Internal Property Path Example Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Shows how to map an environment variable or configuration option to a different internal property name in the runtime configuration. ```json "DD_API_KEY": [ { "type": "string", "default": null, "internalPropertyName": "apiKey" } ] ``` ```javascript config.apiKey ``` -------------------------------- ### Node.js Version Compatibility Check Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Example of how to conditionally use Node.js APIs based on the major version. ```javascript const { NODE_MAJOR } = require('./version') if (NODE_MAJOR >= 20) { // Use Node.js 20+ API } ``` -------------------------------- ### Implement Existing Method in dd-trace Source: https://github.com/datadog/dd-trace-js/blob/master/devdocs/adding-apis.md Example of an existing method within the `dd-trace` core library. ```javascript class DatadogTracer extends Tracer { getVersion() { return this._version } } ``` -------------------------------- ### Implement New Method in dd-trace Source: https://github.com/datadog/dd-trace-js/blob/master/devdocs/adding-apis.md Example of adding a new method to the `dd-trace` core library. ```javascript class DatadogTracer extends Tracer { getEnvironmentInfo() { return { nodeVersion: process.version, platform: process.platform, tracerVersion: this._version } } } ``` -------------------------------- ### Import Ordering Example Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Separate import groups with an empty line and sort alphabetically within each group: Node.js core, third-party, then internal imports. ```javascript import fs from 'node:fs'; import express from 'express'; import { Api } from './api'; import { utils } from './utils'; ``` -------------------------------- ### Install Specific dd-trace Version Source: https://github.com/datadog/dd-trace-js/blob/master/README.md For existing projects that require specific older Node.js versions, install a particular release line by appending the version number. Note that end-of-life release lines do not receive updates. ```sh $ npm install dd-trace@4 # or whatever version you need ``` ```sh $ yarn add dd-trace@4 # or whatever version you need ``` -------------------------------- ### Install Vendored Dependencies Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Use yarn within the 'vendor' directory to install and bundle vendored dependencies for the project. Note that some dependencies might be excluded. ```bash yarn ``` -------------------------------- ### Update Benchmark Fixture Dependencies Source: https://github.com/datadog/dd-trace-js/blob/master/benchmark/sirun/startup/README.md Navigate to the fixture directory, edit package.json to update dependencies, and then run npm install. Ensure node_modules is not committed as it's re-installed by runall.sh. ```sh cd benchmark/sirun/startup/everything-fixture # edit package.json npm install git add package.json package-lock.json ``` -------------------------------- ### Create New Plugin Directory Structure Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Use these bash commands to create the basic directory structure for a new Datadog APM plugin. Copy the base index.js file from an existing plugin to start. ```bash mkdir -p packages/datadog-plugin-/{src,test} cp packages/datadog-plugin-kafkajs/src/index.js packages/datadog-plugin-/src/ ``` -------------------------------- ### Run Plugin Tests with External Services Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Set up and run plugin tests that depend on external services. This involves exporting the `SERVICES` variable, starting Docker Compose, and then running the plugin tests. ```bash export SERVICES="rabbitmq" PLUGINS="amqplib" docker compose up -d $SERVICES yarn services && npm run test:plugins ``` -------------------------------- ### Implement getServiceName in dd-trace Source: https://github.com/datadog/dd-trace-js/blob/master/devdocs/adding-apis.md Example of implementing the `getServiceName` method within the `dd-trace` core library. ```javascript class DatadogTracer extends Tracer { getServiceName() { return this._service } } ``` -------------------------------- ### Conventional Commits PR Title Examples Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Examples of valid Pull Request titles following the Conventional Commits format. ```text feat(appsec): add new WAF rule ``` ```text fix: handle cross section things ``` ```text docs: update contributing guidelines ``` ```text chore(deps): bump express to v5 ``` ```text revert: fix(redis): handle connection timeout ``` -------------------------------- ### OpenTelemetry Metrics API Usage Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md Demonstrates how to record metric data using the OpenTelemetry Metrics API with the Datadog SDK. Ensure 'dd-trace' is initialized and '@opentelemetry/api' is installed. ```javascript require('dd-trace').init() const { metrics } = require('@opentelemetry/api') const meter = metrics.getMeter('my-service', '1.0.0') // Counter - monotonically increasing values const requestCounter = meter.createCounter('http.requests', { description: 'Total HTTP requests', unit: 'requests' }) requestCounter.add(1, { method: 'GET', status: 200 }) // Histogram - distribution of values const durationHistogram = meter.createHistogram('http.duration', { description: 'HTTP request duration', unit: 'ms' }) durationHistogram.record(145, { route: '/api/users' }) // UpDownCounter - can increase and decrease const connectionCounter = meter.createUpDownCounter('active.connections', { description: 'Active connections', unit: 'connections' }) connectionCounter.add(1) // New connection connectionCounter.add(-1) // Connection closed // ObservableGauge - asynchronous observations const cpuGauge = meter.createObservableGauge('system.cpu.usage', { description: 'CPU usage percentage', unit: 'percent' }) cpuGauge.addCallback((result) => { const cpuUsage = process.cpuUsage() result.observe(cpuUsage.system / 1000000, { core: '0' }) }) ``` -------------------------------- ### Nested Properties Configuration Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Illustrates how dot notation in configuration names creates nested objects within the config singleton. This example shows enabling API security. ```json "DD_API_SECURITY_ENABLED": [ { "type": "boolean", "configurationNames": [ "appsec.apiSecurity.enabled", "experimental.appsec.apiSecurity.enabled" ], "default": "true" } ] ``` ```javascript tracer.init({ appsec: { apiSecurity: { enabled: true } } }) ``` ```javascript config.appsec.apiSecurity.enabled === true ``` -------------------------------- ### Emit OpenTelemetry Logs with dd-trace-js Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md Demonstrates how to use the OpenTelemetry Logs API with dd-trace-js for structured logging. Ensure DD_LOGS_OTEL_ENABLED=true is set. This example shows emitting an INFO log within an Express route. ```javascript require('dd-trace').init() const { logs } = require('@opentelemetry/api-logs') const express = require('express') const app = express() const logger = logs.getLogger('my-service', '1.0.0') app.get('/api/users/:id', (req, res) => { logger.emit({ severityText: 'INFO', severityNumber: 9, body: `Processing user request for ID: ${req.params.id}`, }) res.json({ id: req.params.id, name: 'John Doe' }) }) app.listen(3000) ``` -------------------------------- ### Conventional Commit Message Example Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Follow the conventional commit format for commit messages, specifying the type and scope of the change. This helps in automating changelog generation and versioning. ```plaintext type(scope): description Types: feat, fix, docs, refactor, test, chore, ci Example: feat(appsec): add new WAF rule ``` -------------------------------- ### Creating a New Plugin Directory Structure Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Shows the initial directory structure and file copying steps for creating a new plugin for a third-party package. ```bash mkdir -p packages/datadog-plugin-/src cp packages/datadog-plugin-kafkajs/src/index.js packages/datadog-plugin-/src ``` -------------------------------- ### Initialize Benchmark Data and Display Statistics Source: https://github.com/datadog/dd-trace-js/blob/master/benchmark/sirun/diff.html Sets up data variables for previous, current, and goal statistics, then populates HTML elements with calculated summary statistics and their percentage differences. Includes a helper function to update element content and styling based on performance changes. ```javascript const beforeSummary = REPLACE_ME_PREV_DATA const afterSummary = REPLACE_ME_CURR_DATA const goalSummary = REPLACE_ME_GOAL_DATA const diffData = REPLACE_ME_DIFF_DATA const readmes = REPLACE_ME_READMES const beforeStats = summaryStats(beforeSummary) const afterStats = summaryStats(afterSummary) const goalStats = summaryStats(goalSummary) document.getElementById('prev-instructions').innerHTML = Math.floor(beforeStats.instructions) document.getElementById('curr-instructions').innerHTML = Math.floor(afterStats.instructions) diffPctElem('diff-instructions', beforeStats, afterStats, 'instructions') document.getElementById('goal-instructions').innerHTML = Math.floor(goalStats.instructions) diffPctElem('diff-goal-instructions', goalStats, afterStats, 'instructions') document.getElementById('prev-mem').innerHTML = Math.floor(beforeStats.mem) document.getElementById('curr-mem').innerHTML = Math.floor(afterStats.mem) diffPctElem('diff-mem', beforeStats, afterStats, 'mem') document.getElementById('goal-mem').innerHTML = Math.floor(goalStats.mem) diffPctElem('diff-goal-mem', goalStats, afterStats, 'mem') ``` -------------------------------- ### Initialize Tracer and Configure Plugin Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md Initializes the Datadog tracer and enables/configures a specific plugin, such as PostgreSQL. Use this to customize service names for integrations. ```javascript const tracer = require('dd-trace').init() // enable and configure postgresql integration tracer.use('pg', { service: 'pg-cluster' }) ``` -------------------------------- ### Enable Tracer Startup Logs Source: https://github.com/datadog/dd-trace-js/blob/master/MIGRATING.md Startup logs are disabled by default in version 2.0. Enable them using the DD_TRACE_STARTUP_LOGS environment variable. ```bash DD_TRACE_STARTUP_LOGS=true ``` -------------------------------- ### Logging with the log Module Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Shows how to use the internal `log` module for debugging, informational, warning, and error messages. Emphasizes using printf-style formatting for efficiency. ```javascript const log = require('../log') log.debug('Debug message with value: %s', someValue) log.info('Info message') log.warn('Warning with data: %o', objectValue) log.error('Error reading file %s', filepath, err) ``` -------------------------------- ### Run All Benchmark Variants Source: https://github.com/datadog/dd-trace-js/blob/master/benchmark/sirun/README.md Executes all benchmark variants using the provided Node.js script. Navigate to a benchmark directory before running. ```sh node ../run-all-variants.js ``` -------------------------------- ### Run Benchmarks and Summarize Results Source: https://github.com/datadog/dd-trace-js/blob/master/benchmark/sirun/README.md Runs all benchmark variants, summarizes the results using sirun, and processes the output with means.js for tabular display. ```sh node ../run-all-variants.js | sirun --summarize | node ../means.js ``` -------------------------------- ### JSON Configuration with Nested Output Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Demonstrates configuring sampling rules using JSON. The 'toCamelCase' transform is applied to convert keys in the JSON output. ```json "DD_TRACE_SAMPLING_RULES": [ { "type": "json", "configurationNames": ["samplingRules"], "default": "[]", "transform": "toCamelCase" } ] ``` ```bash DD_TRACE_SAMPLING_RULES='[{"sample_rate":0.5,"service":"api"}]' ``` ```javascript config.samplingRules // [{ sampleRate: 0.5, service: 'api' }] ``` -------------------------------- ### Express Span Hook for Request Metadata Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md Use span hooks with the 'express' integration to modify span metadata. This example adds a 'customer.id' tag to the request span based on the incoming request query parameter. ```javascript const tracer = require('dd-trace').init() tracer.use('express', { hooks: { request: (span, req, res) => { span.setTag('customer.id', req.query.id) } } }) ``` -------------------------------- ### Run Benchmarks Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Execute microbenchmarks located in `benchmark/sirun` or `benchmark/index.js` to track performance regressions and improvements, or to compare different approaches. ```sh $ yarn bench ``` -------------------------------- ### Decimal Configuration with Transform Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Shows how to configure the sample rate, which is a decimal value. The 'sampleRate' transform validates and clamps the value to the supported 0..1 range. ```json "DD_TRACE_SAMPLE_RATE": [ { "type": "decimal", "configurationNames": ["sampleRate", "ingestion.sampleRate"], "default": null, "transform": "sampleRate" } ] ``` -------------------------------- ### Initialize Datadog Tracer as OpenTracing global tracer Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md Initializes the Datadog Tracer and sets it as the global tracer for the OpenTracing API. This allows using the OpenTracing API to measure code execution times. ```javascript const tracer = require('dd-trace').init() const opentracing = require('opentracing') opentracing.initGlobalTracer(tracer) ``` -------------------------------- ### tracer.use('pluginName', { options }) Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md This method allows for enabling and configuring specific integrations (plugins) within the Datadog tracer. You can specify a service name or other plugin-specific options. ```APIDOC ## tracer.use('pluginName', { options }) ### Description Enables and configures a specific instrumentation plugin for the Datadog tracer. This allows for customization of how a particular library or framework is traced. ### Method `tracer.use(pluginName, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pluginName** (string) - Required - The name of the plugin to enable (e.g., 'pg', 'express'). - **options** (object) - Optional - Configuration options for the specified plugin. For example, `service` to set the service name. ### Request Example ```javascript const tracer = require('dd-trace').init() // enable and configure postgresql integration tracer.use('pg', { service: 'pg-cluster' }) ``` ### Response This method does not return a value. ``` -------------------------------- ### Run Tracer Core Tests Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Execute the core tracer tests, which focus on the main `packages/dd-trace` package. ```sh $ yarn test:trace:core ``` -------------------------------- ### Array Configuration with Transform Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Illustrates configuring header tags, which are processed as an array. The 'stripColonWhitespace' transform is applied to clean up the input. ```json "DD_TRACE_HEADER_TAGS": [ { "type": "array", "configurationNames": ["headerTags"], "default": "", "transform": "stripColonWhitespace" } ] ``` ```bash DD_TRACE_HEADER_TAGS="x-user-id : user.id, x-team : team" ``` ```javascript tracer.init({ headerTags: ['x-user-id : user.id', 'x-team : team'] }) ``` ```javascript config.headerTags // ['x-user-id:user.id', 'x-team:team'] ``` -------------------------------- ### Run Test File as Entrypoint Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Execute a test file directly using Node.js, particularly when the test expects 'spec file is entrypoint' semantics. The `scripts/mocha-run-file.js` script handles this. You can inject mocha options via `MOCHA_RUN_FILE_CONFIG`. ```bash node scripts/mocha-run-file.js path/to/test.spec.js ``` -------------------------------- ### Event Listener Best Practices Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Avoid adding new listeners if possible. Use monitor symbols like events.errorMonitor and prefer .once() for single-use events. ```javascript emitter.once(events.errorMonitor, handler); process[Symbol.for('dd-trace')].beforeExitHandlers.push(handler); ``` -------------------------------- ### Run Integration Tests with Mocha (Increased Timeout) Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Execute integration test files using Mocha, which often require a longer timeout. Specify the path to the integration test file. ```bash ./node_modules/.bin/mocha --timeout 60000 path/to/test.spec.js ``` -------------------------------- ### Run Plugin Tests with PLUGINS Environment Variable Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Execute tests for specific plugins by setting the `PLUGINS` environment variable. Use a pipe-delimited string for multiple plugins. ```bash PLUGINS="amqplib" npm run test:plugins # pipe-delimited for multiple: PLUGINS="amqplib|bluebird" ``` -------------------------------- ### Run Core Library Tests Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Execute tests for the core library, specifically the `packages/datadog-core` package. ```sh $ yarn test:core ``` -------------------------------- ### Test Subsystem Method Source: https://github.com/datadog/dd-trace-js/blob/master/devdocs/adding-apis.md Use `describeSubsystem` to test subsystem methods. ```javascript describeSubsystem('appsec', 'checkPermission', true) ``` -------------------------------- ### Logging Errors with Context Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Demonstrates the correct way to log errors, including passing the error object as the last argument, optionally with additional context like a filename. ```javascript log.error('Error processing request', err) // or with additional context: log.error('Error reading file %s', filename, err) ``` -------------------------------- ### Handle Subsystem Method Bridging Source: https://github.com/datadog/dd-trace-js/blob/master/devdocs/adding-apis.md Use the `subsystem:method` format in `handleEvent` for subsystem methods. ```javascript handleEvent('appsec:checkPermission') ``` -------------------------------- ### Generate Performance Bar Charts Source: https://github.com/datadog/dd-trace-js/blob/master/benchmark/sirun/diff.html Iterates through benchmark data to create bar charts for each test and variant. It displays 'instructions' and other summary metrics, using colors to visually represent performance changes (red for worse, green for better). ```javascript Chart.defaults.plugins.legend.display = false const charts = document.getElementById('charts') for (const testName in diffData) { const test = diffData[testName] const testDiv = document.createElement('div', {}) testDiv.id = testName testDiv.className = 'test' testDiv.innerHTML += '

' + testName + '

' if (readmes[testName]) { testDiv.innerHTML += marked(readmes[testName]) } charts.appendChild(testDiv) for (const variantName in test) { const variantDiv = document.createElement('div', {}) variantDiv.id = variantName variantDiv.className = 'variant' testDiv.appendChild(variantDiv) variantDiv.innerHTML += '

' + variantName + '

' if (variant.nodeVersion) { variantDiv.innerHTML += `
REPLACE_ME_PREVREPLACE_ME_CURR
Node.js Version${variant.nodeVersion.prev}${variant.nodeVersion.curr}
` } const canvas = document.createElement('canvas') canvas.height = '50' canvas.width = '400' variantDiv.appendChild(canvas) const ctx = canvas.getContext('2d') const data = [ variant.instructions, ...Object.keys(variant.summary).map(name => variant.summary[name].mean) ] const chart = new Chart(ctx, { type: 'bar', data: { labels: ['instructions', ...Object.keys(variant.summary)], datasets: [ { data, backgroundColor: data.map(n => getColor(n, 0.2)), borderColor: data.map(n => getColor(n, 1)) } ] } }) } } ``` -------------------------------- ### Run ESLint Linter Source: https://github.com/datadog/dd-trace-js/blob/master/CONTRIBUTING.md Execute the ESLint linter to ensure new code conforms to coding standards. This command also checks the `LICENSE-3rdparty.csv` file and scans dependencies for vulnerabilities. ```sh $ yarn lint ``` -------------------------------- ### Run Unit Tests with Mocha Source: https://github.com/datadog/dd-trace-js/blob/master/AGENTS.md Execute individual unit test files using Mocha. Ensure the path to the test file is correctly specified. ```bash ./node_modules/.bin/mocha path/to/test.spec.js ``` -------------------------------- ### Initialize dd-trace-js Tracer Source: https://github.com/datadog/dd-trace-js/blob/master/docs/API.md Initializes the dd-trace-js tracer. This is a prerequisite for using its tracing capabilities. The TracerProvider is then registered. ```javascript const tracer = require('dd-trace').init() const tracerProvider = new tracer.TracerProvider() tracerProvider.register() ``` -------------------------------- ### Configure Tracer Enabled State Source: https://github.com/datadog/dd-trace-js/blob/master/MIGRATING.md The 'enabled' configuration option is no longer available programmatically. Use the DD_TRACE_ENABLED environment variable instead. ```bash DD_TRACE_ENABLED=true|false ``` -------------------------------- ### Shell command for coverage output layout Source: https://github.com/datadog/dd-trace-js/blob/master/integration-tests/coverage/README.md Shows the directory structure for intermediate and final coverage reports generated by the harness. ```shell .nyc_output/integration-tests-collector-