### YAML Configuration Example for PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md An example of a PingOps SDK configuration using YAML format. This configuration includes key settings such as API key, base URL, service name, and export mode, similar to the JSON example. ```yaml apiKey: your-api-key baseUrl: https://api.pingops.com serviceName: my-service debug: false exportMode: batched batchSize: 50 batchTimeout: 5000 ``` -------------------------------- ### PingOps Configuration File Examples Source: https://context7.com/pingops-io/pingops-js/llms.txt Examples of PingOps configuration files in JSON and YAML formats. These files allow for setting various PingOps parameters, with environment variables taking precedence. ```json { "apiKey": "your-api-key", "baseUrl": "https://api.pingops.com", "serviceName": "my-service", "debug": false, "exportMode": "batched", "batchSize": 50, "batchTimeout": 5000, "captureRequestBody": false, "captureResponseBody": false, "maxRequestBodySize": 4096, "maxResponseBodySize": 4096, "headersAllowList": ["user-agent", "content-type", "x-request-id"], "headersDenyList": ["authorization", "cookie"], "domainAllowList": [ { "domain": "api.github.com", "paths": ["/repos"] }, { "domain": ".openai.com", "captureRequestBody": true, "captureResponseBody": true } ], "domainDenyList": [ { "domain": "localhost" } ] } ``` ```yaml # pingops.config.yaml apiKey: your-api-key baseUrl: https://api.pingops.com serviceName: my-service debug: false exportMode: batched batchSize: 50 batchTimeout: 5000 captureRequestBody: false captureResponseBody: false maxRequestBodySize: 4096 maxResponseBodySize: 4096 headersAllowList: - user-agent - content-type - x-request-id headersDenyList: - authorization - cookie domainAllowList: - domain: api.github.com paths: - /repos - domain: .openai.com captureRequestBody: true captureResponseBody: true domainDenyList: - domain: localhost ``` -------------------------------- ### startTrace Usage Example Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Demonstrates how to use `startTrace` to create a request-scoped trace for a webhook endpoint, correlating calls and using a stable trace ID. ```APIDOC ## Example: request-scoped trace ### Description This example shows how to use `startTrace` within a webhook handler to create a trace that encompasses all operations related to that specific request. It also demonstrates how to extract and return the trace ID in the response headers. ### Code ```typescript import { startTrace, getActiveTraceId, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "...", serviceName: "my-api" }); app.post("/webhook", async (req, res) => { const result = await startTrace( { attributes: { userId: req.user?.id, sessionId: req.sessionId, tags: ["webhook"], metadata: { provider: req.body.provider }, }, seed: req.headers["x-request-id"] ?? undefined, }, async () => { await callExternalApi(req.body); return { ok: true }; } ); const traceId = getActiveTraceId(); res.setHeader("X-Trace-Id", traceId ?? ""); res.json(result); }); ``` ``` -------------------------------- ### JSON Configuration Example for PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md An example of a PingOps SDK configuration using JSON format. This configuration specifies essential parameters like API key, base URL, service name, and export mode. ```json { "apiKey": "your-api-key", "baseUrl": "https://api.pingops.com", "serviceName": "my-service", "debug": false, "exportMode": "batched", "batchSize": 50, "batchTimeout": 5000, "captureRequestBody": false, "captureResponseBody": false } ``` -------------------------------- ### Install PingOps SDK (npm/pnpm) Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Instructions for installing the PingOps SDK using either pnpm or npm package managers. Requires Node.js version 20 or later. ```bash pnpm add @pingops/sdk ``` ```bash npm install @pingops/sdk ``` -------------------------------- ### Express Middleware Integration Source: https://context7.com/pingops-io/pingops-js/llms.txt Example of using startTrace in an Express application to correlate all outgoing API calls within a request to the same trace with user context. ```APIDOC ## Express Middleware Integration ### Description This example demonstrates how to integrate the `startTrace` function into an Express.js application to automatically trace all outgoing API calls made within a request. ### Method `app.post("/webhook", async (req, res) => { ... });` ### Endpoint `/webhook` (POST) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Assumes a JSON request body with properties like `event_type`, `provider`, `id`, `charge_id`, `customer_email`. ### Request Example ```typescript import express from "express"; import { startTrace, getActiveTraceId, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-api", exportMode: "batched" }); const app = express(); app.use(express.json()); app.post("/webhook", async (req, res) => { const result = await startTrace( { attributes: { userId: req.user?.id, sessionId: req.sessionId, tags: ["webhook", req.body.event_type], metadata: { provider: req.body.provider, webhookId: req.body.id } }, seed: req.headers["x-request-id"] as string }, async () => { const paymentStatus = await fetch("https://api.stripe.com/v1/charges/" + req.body.charge_id, { headers: { Authorization: `Bearer ${process.env.STRIPE_KEY}` } }); await fetch("https://api.sendgrid.com/v3/mail/send", { method: "POST", headers: { Authorization: `Bearer ${process.env.SENDGRID_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ to: [{ email: req.body.customer_email }], subject: "Payment Received", content: [{ type: "text/plain", value: "Thank you!" }] }) }); return { processed: true }; } ); const traceId = getActiveTraceId(); res.setHeader("X-Trace-Id", traceId ?? ""); res.json(result); }); app.listen(3000); ``` ### Response #### Success Response (200) - **result** (object) - The return value of the callback function, indicating processing status. - **X-Trace-Id** (string) - The trace ID for the request, useful for debugging. #### Response Example ```json { "processed": true } ``` ``` -------------------------------- ### Install @pingops/otel Package Source: https://github.com/pingops-io/pingops-js/blob/main/packages/otel/README.md Installs the @pingops/otel package using pnpm. This is the first step to integrate PingOps tracing into your Node.js application. ```bash pnpm add @pingops/otel ``` -------------------------------- ### startTrace Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Starts a new trace, sets PingOps attributes, runs a function within that context, and returns the function's result. Spans created within the function are part of this trace. ```APIDOC ## startTrace(options, fn) ### Description Starts a new trace, sets PingOps attributes (e.g. `userId`, `sessionId`, tags, metadata) in context, runs the given function inside that context, and returns the function’s result. Any spans created inside the function (including automatic HTTP/fetch spans) are part of this trace and carry the same context. ### Parameters - `options.attributes` (PingopsTraceAttributes) - Optional: Attributes to attach to the trace and propagate to spans. - `options.seed` (string) - Optional: When provided, a deterministic trace ID is derived from it. - `fn` (() => T | Promise) - Required: Your code to run inside the new trace and attribute context. ### Returns - `Promise` - The result of `fn`. ### Request Example ```typescript import { startTrace, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "...", serviceName: "my-api" }); const data = await startTrace( { attributes: { userId: "user-123", sessionId: "sess-456", tags: ["checkout", "v2"], metadata: { plan: "pro", region: "us" }, captureRequestBody: true, captureResponseBody: true, }, seed: "order-789", // optional: stable trace ID for this order }, async () => { const res = await fetch("https://api.stripe.com/v1/charges", { ... }); return res.json(); } ); ``` ``` -------------------------------- ### startTrace Function Source: https://context7.com/pingops-io/pingops-js/llms.txt Starts a new trace with optional attributes and runs a callback function within that trace context. All spans created inside the callback inherit the trace context and attributes. ```APIDOC ## startTrace ### Description Starts a new trace with optional attributes (userId, sessionId, tags, metadata) and runs the callback function within that trace context. All spans created inside the callback (including automatic HTTP/fetch spans) inherit the trace context and attributes. ### Method `startTrace(options, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - Configuration for the trace. - **attributes** (object) - Optional - Key-value pairs to associate with the trace. - **userId** (string) - Optional - Identifier for the user. - **sessionId** (string) - Optional - Identifier for the session. - **tags** (array of strings) - Optional - Tags for categorizing the trace. - **metadata** (object) - Optional - Additional metadata for the trace. - **captureRequestBody** (boolean) - Optional - Whether to capture request bodies. - **captureResponseBody** (boolean) - Optional - Whether to capture response bodies. - **seed** (string) - Optional - A deterministic seed for generating the trace ID. - **callback** (function) - Required - An asynchronous function to execute within the trace context. ### Request Example ```typescript import { startTrace, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-api" }); const result = await startTrace( { attributes: { userId: "user-123", sessionId: "sess-456", tags: ["checkout", "v2", "production"], metadata: { plan: "pro", region: "us-east-1" }, captureRequestBody: true, captureResponseBody: true }, seed: "order-789" }, async () => { const stripeRes = await fetch("https://api.stripe.com/v1/charges", { method: "POST", headers: { "Authorization": "Bearer sk_test_xxx", "Content-Type": "application/x-www-form-urlencoded" }, body: "amount=2000¤cy=usd" }); return await stripeRes.json(); } ); console.log(result); ``` ### Response #### Success Response (200) - **result** (any) - The return value of the callback function. #### Response Example ```json { "id": "ch_xxx", "amount": 2000, "currency": "usd" } ``` ``` -------------------------------- ### Start a Trace with PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Starts a new trace, sets PingOps attributes, executes a function within that context, and returns the function's result. Spans created within the function are associated with this trace. Supports custom attributes like userId, sessionId, tags, metadata, and request/response body capture settings. An optional seed can be provided for deterministic trace IDs. ```typescript import { startTrace, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "...", serviceName: "my-api" }); const data = await startTrace( { attributes: { userId: "user-123", sessionId: "sess-456", tags: ["checkout", "v2"], metadata: { plan: "pro", region: "us" }, captureRequestBody: true, captureResponseBody: true, }, seed: "order-789", // optional: stable trace ID for this order }, async () => { const res = await fetch("https://api.stripe.com/v1/charges", { ... }); return res.json(); } ); ``` ```typescript import { startTrace, getActiveTraceId, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "...", serviceName: "my-api" }); app.post("/webhook", async (req, res) => { const result = await startTrace( { attributes: { userId: req.user?.id, sessionId: req.sessionId, tags: ["webhook"], metadata: { provider: req.body.provider }, }, seed: req.headers["x-request-id"] ?? undefined, }, async () => { await callExternalApi(req.body); return { ok: true }; } ); const traceId = getActiveTraceId(); res.setHeader("X-Trace-Id", traceId ?? ""); res.json(result); }); ``` -------------------------------- ### Start Trace with Attributes and Callback - TypeScript Source: https://context7.com/pingops-io/pingops-js/llms.txt Initiates a new trace with specified attributes (userId, sessionId, tags, metadata) and executes a provided asynchronous callback function within that trace's context. All operations within the callback, including automatic HTTP/fetch requests, are associated with this trace. Dependencies include the '@pingops/sdk' package. ```typescript import { startTrace, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-api" }); // Basic usage with user context const result = await startTrace( { attributes: { userId: "user-123", sessionId: "sess-456", tags: ["checkout", "v2", "production"], metadata: { plan: "pro", region: "us-east-1" }, captureRequestBody: true, // Override for this trace only captureResponseBody: true }, seed: "order-789" // Optional: deterministic trace ID from this seed }, async () => { // All HTTP calls inside this callback are part of the same trace const stripeRes = await fetch("https://api.stripe.com/v1/charges", { method: "POST", headers: { "Authorization": "Bearer sk_test_xxx", "Content-Type": "application/x-www-form-urlencoded" }, body: "amount=2000¤cy=usd" }); const openaiRes = await fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Authorization": "Bearer sk-xxx", "Content-Type": "application/json" }, body: JSON.stringify({ model: "gpt-4", messages: [{ role: "user", content: "Hello" }] }) }); return { stripe: await stripeRes.json(), openai: await openaiRes.json() }; } ); console.log(result); // { stripe: { id: "ch_xxx", ... }, openai: { choices: [...], ... } } ``` -------------------------------- ### Gracefully Shutdown PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Provides an example of how to gracefully shut down the PingOps SDK, ensuring all pending spans are flushed before the application exits. This is typically handled in response to termination signals. ```typescript import { shutdownPingops } from "@pingops/sdk"; process.on("SIGTERM", async () => { await shutdownPingops(); process.exit(0); }); ``` -------------------------------- ### Integrate PingOps with OpenTelemetry in TypeScript Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Integrate PingOps' exporter and filtering into an existing OpenTelemetry setup by using `PingopsSpanProcessor`. This allows leveraging PingOps features without replacing your current OpenTelemetry SDK configuration. ```typescript import { NodeSDK } from "@opentelemetry/sdk-node"; import { PingopsSpanProcessor } from "@pingops/otel"; const sdk = new NodeSDK({ spanProcessors: [ new PingopsSpanProcessor({ apiKey: "your-api-key", baseUrl: "https://api.pingops.com", serviceName: "my-service", exportMode: "batched", domainAllowList: [{ domain: "api.example.com" }], }), ], // your existing instrumentations, resource, etc. }); sdk.start(); ``` -------------------------------- ### Gracefully Shut Down PingOps SDK Source: https://context7.com/pingops-io/pingops-js/llms.txt This snippet demonstrates how to gracefully shut down the PingOps SDK, ensuring all remaining spans are flushed. It includes examples for handling SIGTERM and SIGINT signals, as well as for serverless environments like AWS Lambda. ```typescript import { initializePingops, shutdownPingops, startTrace } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-service" }); // Handle graceful shutdown process.on("SIGTERM", async () => { console.log("Received SIGTERM, shutting down..."); await shutdownPingops(); console.log("PingOps shutdown complete"); process.exit(0); }); process.on("SIGINT", async () => { console.log("Received SIGINT, shutting down..."); await shutdownPingops(); process.exit(0); }); // For serverless: ensure flush before function ends export async function handler(event: any) { const result = await startTrace( { attributes: { tags: ["lambda"] } }, async () => { return await fetch("https://api.example.com/process", { method: "POST", body: JSON.stringify(event) }).then(r => r.json()); } ); // Flush remaining spans before Lambda freezes await shutdownPingops(); return result; } ``` -------------------------------- ### Integrate PingOps with OpenTelemetry Source: https://context7.com/pingops-io/pingops-js/llms.txt This snippet shows how to use the PingopsSpanProcessor to integrate PingOps with an existing OpenTelemetry setup. It configures the processor with various options like API key, base URL, service name, export mode, batching, and filtering rules for domains and headers. ```typescript import { NodeSDK } from "@opentelemetry/sdk-node"; import { PingopsSpanProcessor } from "@pingops/otel"; import { HttpInstrumentation } from "@opentelemetry/instrumentation-http"; // Create PingOps processor const pingopsProcessor = new PingopsSpanProcessor({ apiKey: "your-api-key", baseUrl: "https://api.pingops.com", serviceName: "my-service", exportMode: "batched", batchSize: 50, batchTimeout: 5000, debug: false, // Domain filtering domainAllowList: [ { domain: "api.github.com", paths: ["/repos", "/users"] }, { domain: ".openai.com", captureRequestBody: true, captureResponseBody: true, headersAllowList: ["x-request-id"] }, { domain: "api.stripe.com" } ], domainDenyList: [ { domain: "localhost" }, { domain: "internal.corp.local" } ], // Header filtering headersAllowList: ["user-agent", "content-type", "x-request-id"], headersDenyList: ["authorization", "cookie", "x-api-key"], // Body capture captureRequestBody: false, captureResponseBody: false, maxRequestBodySize: 4096, maxResponseBodySize: 4096 }); // Use with existing OpenTelemetry NodeSDK const sdk = new NodeSDK({ spanProcessors: [pingopsProcessor], instrumentations: [new HttpInstrumentation()] }); sdk.start(); // Shutdown process.on("SIGTERM", async () => { await sdk.shutdown(); process.exit(0); }); ``` -------------------------------- ### Get Active Trace ID with PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Retrieves the trace ID of the currently active span. Returns undefined if no active span is present. This is useful for correlating logs or responses with a specific trace. ```typescript import { getActiveTraceId } from "@pingops/sdk"; const traceId = getActiveTraceId(); console.log("Current trace:", traceId); ``` -------------------------------- ### Get Active Span ID with PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Retrieves the span ID of the currently active span. Returns undefined if no active span is present. This can be used for detailed debugging within a specific operation. ```typescript import { getActiveSpanId } from "@pingops/sdk"; const spanId = getActiveSpanId(); ``` -------------------------------- ### Get Active Trace and Span IDs - TypeScript Source: https://context7.com/pingops-io/pingops-js/llms.txt Retrieves the current trace ID and span ID within an active trace context. This is useful for logging, debugging, and correlating events across different parts of an application. The functions return `undefined` when called outside of an active trace. Requires '@pingops/sdk'. ```typescript import { getActiveTraceId, getActiveSpanId, startTrace, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-service" }); await startTrace({ attributes: { userId: "user-123" } }, async () => { const traceId = getActiveTraceId(); const spanId = getActiveSpanId(); console.log(`Trace ID: ${traceId}`); // e.g., "a1b2c3d4e5f6789012345678901234ab" console.log(`Span ID: ${spanId}`); // e.g., "0123456789abcdef" // Include in logs for correlation console.log(JSON.stringify({ message: "Processing request", traceId, spanId, timestamp: new Date().toISOString() })); await fetch("https://api.example.com/data"); }); // Outside trace context console.log(getActiveTraceId()); // undefined console.log(getActiveSpanId()); // undefined ``` -------------------------------- ### Auto-initialize PingOps SDK with --require Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Demonstrates how to auto-initialize the PingOps SDK by using the Node.js --require flag. This method runs the SDK registration before any application code, and requires setting environment variables for API key, base URL, and service name. ```bash node --require @pingops/sdk/register your-app.js export PINGOPS_API_KEY="your-api-key" export PINGOPS_BASE_URL="https://api.pingops.com" export PINGOPS_SERVICE_NAME="my-service" ``` -------------------------------- ### Initialize PingOps SDK with Configuration Object Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Demonstrates how to initialize the PingOps SDK using a configuration object directly within the code. This method is useful for setting up the SDK with dynamic or environment-variable-based configurations. ```typescript import { initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-service", apiKey: process.env.PINGOPS_API_KEY, exportMode: "immediate", // e.g. for serverless }); ``` -------------------------------- ### Manually initialize PingOps SDK Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Illustrates manual initialization of the PingOps SDK by calling the 'initializePingops' function with a configuration object. This approach is useful for programmatic configuration or when using feature flags. It must be called before any HTTP clients are loaded or used. ```typescript import { initializePingops } from "@pingops/sdk"; // Before importing or using any HTTP clients initializePingops({ apiKey: process.env.PINGOPS_API_KEY, baseUrl: "https://api.pingops.com", serviceName: "my-service", }); import axios from "axios"; // ... rest of your application ``` -------------------------------- ### Manually initialize PingOps SDK from config file Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Demonstrates manual initialization of the PingOps SDK using a configuration file path. The SDK supports both JSON and YAML formats for configuration files. Environment variables will override values from the config file. ```typescript import { initializePingops } from "@pingops/sdk"; initializePingops("./pingops.config.yaml"); // or initializePingops({ configFile: "./pingops.config.json" }); ``` -------------------------------- ### Auto-initialize PingOps SDK by importing register Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Shows how to auto-initialize the PingOps SDK by importing the '@pingops/sdk/register' module at the very beginning of your application. This ensures instrumentation is applied before any HTTP client is loaded or used. ```typescript // Must be first — before axios, node-fetch, or any code that makes HTTP requests import "@pingops/sdk/register"; import axios from "axios"; // ... rest of your application ``` -------------------------------- ### Auto-initialize PingOps SDK with register Source: https://context7.com/pingops-io/pingops-js/llms.txt Automatically initializes the PingOps SDK using environment variables or a configuration file when the `@pingops/sdk/register` module is imported. This must be done before any HTTP clients are loaded. It supports both ESM imports and the Node.js `--require` flag for pre-application execution. ```bash # Option A: Using Node.js --require flag (runs before any application code) export PINGOPS_API_KEY="your-api-key" export PINGOPS_BASE_URL="https://api.pingops.com" export PINGOPS_SERVICE_NAME="my-service" export PINGOPS_DEBUG="true" export PINGOPS_EXPORT_MODE="batched" export PINGOPS_BATCH_SIZE="50" export PINGOPS_BATCH_TIMEOUT="5000" node --require @pingops/sdk/register your-app.js # Option B: Using config file export PINGOPS_CONFIG_FILE="./pingops.config.yaml" node --require @pingops/sdk/register your-app.js ``` ```typescript # Option C: Import register first in your application import "@pingops/sdk/register"; // Must be first import! import axios from "axios"; import express from "express"; // ... rest of your application ``` -------------------------------- ### Initialize PingOps SDK Programmatically Source: https://context7.com/pingops-io/pingops-js/llms.txt Initializes the PingOps SDK by configuring an OpenTelemetry NodeSDK instance with various options. This function must be called before any HTTP clients are loaded and is idempotent. It allows for programmatic configuration of API keys, base URLs, service names, export modes, batching settings, request/response capture, header filtering, and domain-specific configurations. ```typescript import { initializePingops } from "@pingops/sdk"; // Option 1: Programmatic configuration initializePingops({ apiKey: "your-api-key", baseUrl: "https://api.pingops.com", serviceName: "my-service", debug: false, exportMode: "batched", // "batched" (default) or "immediate" for serverless batchSize: 50, // Spans per batch (default: 50) batchTimeout: 5000, // Flush interval in ms (default: 5000) captureRequestBody: false, // Capture request bodies globally captureResponseBody: false, // Capture response bodies globally maxRequestBodySize: 4096, // Max request body size in bytes maxResponseBodySize: 4096, // Max response body size in bytes headersAllowList: ["user-agent", "content-type"], headersDenyList: ["authorization", "cookie"], domainAllowList: [ { domain: "api.github.com", paths: ["/repos"] }, { domain: ".openai.com", captureRequestBody: true, captureResponseBody: true } ], domainDenyList: [{ domain: "internal.corp.local" }] }); // Option 2: From config file path initializePingops("./pingops.config.yaml"); // Option 3: From config file wrapper initializePingops({ configFile: "./pingops.config.json" }); ``` -------------------------------- ### PingopsTraceAttributes Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Defines the structure for attributes that can be passed to the `startTrace` function to configure trace and span properties. ```APIDOC ## PingopsTraceAttributes ### Description Type for attributes you can pass into `startTrace({ attributes })`: ### Fields | Field | Type | Description | |---|---|---| | `traceId` | `string` | Override trace ID (otherwise one is generated or derived from `seed`) | | `userId` | `string` | User identifier | | `sessionId` | `string` | Session identifier | | `tags` | `string[]` | Tags for the trace | | `metadata` | `Record` | Key-value metadata | | `captureRequestBody` | `boolean` | Override request body capture for spans in this trace | | `captureResponseBody` | `boolean` | Override response body capture for spans in this trace | ``` -------------------------------- ### Configure Domain Allow/Deny Lists in TypeScript Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Initialize PingOps with specific domain allow and deny lists to control which domains and paths are captured. Rules can include exact or suffix domain matching, path prefixes, and header/body capture overrides. ```typescript initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-service", domainAllowList: [ { domain: "api.github.com", paths: ["/repos"] }, { domain: ".openai.com" }, // suffix match { domain: "generativelanguage.googleapis.com", captureRequestBody: true, captureResponseBody: true, }, ], domainDenyList: [ { domain: "internal.corp.local" }, ], }); ``` -------------------------------- ### Express Middleware for Trace Correlation - TypeScript Source: https://context7.com/pingops-io/pingops-js/llms.txt Demonstrates integrating `startTrace` into an Express.js application to ensure all outgoing API calls within a request are correlated to the same trace. It extracts user context and request IDs to enrich trace attributes. Requires Express.js and '@pingops/sdk'. ```typescript import express from "express"; import { startTrace, getActiveTraceId, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-api", exportMode: "batched" }); const app = express(); app.use(express.json()); app.post("/webhook", async (req, res) => { const result = await startTrace( { attributes: { userId: req.user?.id, sessionId: req.sessionId, tags: ["webhook", req.body.event_type], metadata: { provider: req.body.provider, webhookId: req.body.id } }, seed: req.headers["x-request-id"] as string // Stable trace ID }, async () => { // Call external APIs - all captured under the same trace const paymentStatus = await fetch("https://api.stripe.com/v1/charges/" + req.body.charge_id, { headers: { Authorization: `Bearer ${process.env.STRIPE_KEY}` } }); await fetch("https://api.sendgrid.com/v3/mail/send", { method: "POST", headers: { Authorization: `Bearer ${process.env.SENDGRID_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ to: [{ email: req.body.customer_email }], subject: "Payment Received", content: [{ type: "text/plain", value: "Thank you!" }] }) }); return { processed: true }; } ); // Return trace ID in response for debugging const traceId = getActiveTraceId(); res.setHeader("X-Trace-Id", traceId ?? ""); res.json(result); }); app.listen(3000); ``` -------------------------------- ### Configure Header Allow/Deny Lists in TypeScript Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Set up global header allow and deny lists to control which HTTP headers are included in captured spans. Domain-specific rules can refine these settings. The deny list takes precedence over the allow list. ```typescript initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-service", headersAllowList: ["user-agent", "x-request-id", "content-type"], headersDenyList: ["authorization", "cookie", "x-api-key"], }); ``` -------------------------------- ### Immediate Span Export for Serverless with PingopsSpanProcessor Source: https://github.com/pingops-io/pingops-js/blob/main/packages/otel/README.md Shows how to configure PingopsSpanProcessor for immediate export mode, suitable for serverless environments. This ensures spans are sent before the function terminates, preventing data loss. It requires an API key, base URL, and service name. ```typescript const processor = new PingopsSpanProcessor({ apiKey: "your-api-key", baseUrl: "https://api.pingops.com", serviceName: "my-service", exportMode: "immediate", // Spans are sent immediately }); ``` -------------------------------- ### Basic Batched Span Export with PingopsSpanProcessor Source: https://github.com/pingops-io/pingops-js/blob/main/packages/otel/README.md Demonstrates basic usage of PingopsSpanProcessor in batched mode. It configures the processor with an API key, base URL, service name, and sets the export mode to 'batched' with custom batch size and timeout. The processor is then added to an OpenTelemetry NodeTracerProvider. ```typescript import { PingopsSpanProcessor } from "@pingops/otel"; import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node"; const processor = new PingopsSpanProcessor({ apiKey: "your-api-key", // or set PINGOPS_API_KEY env var baseUrl: "https://api.pingops.com", serviceName: "my-service", exportMode: "batched", // default batchSize: 50, batchTimeout: 5000, }); const tracerProvider = new NodeTracerProvider(); tracerProvider.addSpanProcessor(processor); tracerProvider.register(); ``` -------------------------------- ### getActiveTraceId Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Retrieves the trace ID of the currently active span. Returns undefined if no trace is active. ```APIDOC ## getActiveTraceId() ### Description Returns the trace ID of the currently active span, or `undefined` if there is none. ### Returns - `string | undefined` - The active trace ID or undefined. ### Request Example ```typescript import { getActiveTraceId } from "@pingops/sdk"; const traceId = getActiveTraceId(); console.log("Current trace:", traceId); ``` ``` -------------------------------- ### getActiveSpanId Source: https://github.com/pingops-io/pingops-js/blob/main/packages/sdk/README.md Retrieves the span ID of the currently active span. Returns undefined if no span is active. ```APIDOC ## getActiveSpanId() ### Description Returns the span ID of the currently active span, or `undefined` if there is none. ### Returns - `string | undefined` - The active span ID or undefined. ### Request Example ```typescript import { getActiveSpanId } from "@pingops/sdk"; const spanId = getActiveSpanId(); ``` ``` -------------------------------- ### getActiveTraceId / getActiveSpanId Source: https://context7.com/pingops-io/pingops-js/llms.txt Returns the trace ID or span ID of the currently active span. Useful for logging, debugging, or including in responses. ```APIDOC ## getActiveTraceId / getActiveSpanId ### Description These utility functions retrieve the current trace ID and span ID from the active context. They are invaluable for correlating logs and debugging distributed systems. ### Method `getActiveTraceId()` `getActiveSpanId()` ### Parameters None ### Request Example ```typescript import { getActiveTraceId, getActiveSpanId, startTrace, initializePingops } from "@pingops/sdk"; initializePingops({ baseUrl: "https://api.pingops.com", serviceName: "my-service" }); await startTrace({ attributes: { userId: "user-123" } }, async () => { const traceId = getActiveTraceId(); const spanId = getActiveSpanId(); console.log(`Trace ID: ${traceId}`); console.log(`Span ID: ${spanId}`); console.log(JSON.stringify({ message: "Processing request", traceId, spanId, timestamp: new Date().toISOString() })); await fetch("https://api.example.com/data"); }); console.log(getActiveTraceId()); // undefined console.log(getActiveSpanId()); // undefined ``` ### Response #### Success Response (200) - **getActiveTraceId()** (string | undefined) - The current trace ID, or undefined if not in an active trace context. - **getActiveSpanId()** (string | undefined) - The current span ID, or undefined if not in an active span context. #### Response Example ``` Trace ID: a1b2c3d4e5f6789012345678901234ab Span ID: 0123456789abcdef { "message": "Processing request", "traceId": "a1b2c3d4e5f6789012345678901234ab", "spanId": "0123456789abcdef", "timestamp": "2023-10-27T10:00:00.000Z" } undefined undefined ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.