由 Jovan K. 出售

Official Node.js APM agent for Elastic Observability that automatically captures errors, traces, and performance metrics from Node.js applications and sends data to your Elastic Stack deployment.
This block provides the core source of the Elastic APM Node.js agent (user@example.com), including the APM client, instrumentation engine, cloud metadata detection, metrics, tracing context, and configuration subsystems. It targets backend Node.js engineers who need to embed APM telemetry collection directly, extend the agent, or build custom APM tooling without relying on the published npm package binary.
apm-client/ - HTTP and no-op APM server client implementations; handles intake stream, keepalive connections, and central config pollingcloud-metadata/ - Detects cloud provider metadata from AWS, Azure, and GCP metadata endpointsconfig/ - Configuration schema, normalization, and parsing logic for all agent optionsfilters/ - Field-name sanitization filters for request/response datainstrumentation/ - Core auto-instrumentation engine: shimmer, run-context managers, span/transaction lifecycle, and module patchersmetrics/ - Metric collection registry built on measured-reporting; counters, histograms, and queue metricsmiddleware/ - Connect/Express-compatible middleware helpersopentelemetry-bridge/ - OTel API bridge so OTel-instrumented code emits APM spansopentelemetry-metrics/ - OTel SDK metrics integrationtracecontext/ - W3C traceparent/tracestate header parsing and serializationInflightEventSet.js - Tracks in-flight transactions and spans to manage flush orderingactivation-method.js - Detects how the agent was activated (require, --require, etc.)agent.js - Root Agent class; the main facade over all subsystemsasync-hooks-polyfill.js - Polyfill for older Node async hooks API surfaceconstants.js - Shared string/symbol constants (context manager names, etc.)errors.js - Error capture and normalization utilitieshttp-request.js - Low-level uninstrumented HTTP helper used internallylambda.js - AWS Lambda handler detection and wrapping helpersload-source-map.js - Source-map loading for stack trace enhancement启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 94a9bbf9ecef7f87…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
logging.jsparsers.js - HTTP request/response parsers for extracting APM-relevant fieldspropwrap.js - Property descriptor wrapping utilitystacktraces.js - Stack trace collection and cullingsymbols.js - Global Symbol registry for cross-module private propertieswildcard-matcher.js - Wildcard/glob pattern matching for config optionsnpm install @elastic/ecs-pino-format @opentelemetry/api @opentelemetry/core \
@opentelemetry/sdk-metrics after-all-results agentkeepalive \
async-value-promise basic-auth breadth-filter cookie core-util-is \
end-of-stream error-callsites error-stack-parser escape-string-regexp \
fast-safe-stringify fast-stream-to-buffer http-headers \
import-in-the-middle json-bigint lru-cache measured-reporting \
module-details-from-path monitor-event-loop-delay object-filter-sequence \
pino require-in-the-middle readable-stream semver stream-chopper \
source-map
No native addons, no pod install, no Android linking required. Node.js >=14.5 is required; Node >=18 is recommended for AsyncLocalStorage run-context support and native fetch instrumentation.
source/ directory into your project, e.g. src/apm-core/.tsconfig.json add a path alias if using TypeScript:
{
"compilerOptions": {
"paths": {
"apm-core/*": ["./src/apm-core/*"]
}
}
}
ELASTIC_APM_SERVER_URL=https://your-apm-server:8200
ELASTIC_APM_SECRET_TOKEN=your_token
ELASTIC_APM_SERVICE_NAME=my-service
ELASTIC_APM_ENVIRONMENT=production
--import or --loader (see upstream docs), because import-in-the-middle hooks require the module loader to be active before user modules resolve.import { HttpApmClient } from './apm-core/apm-client/http-apm-client/index.js';
new HttpApmClient(options: {
agentName: string;
agentVersion: string;
serviceName: string;
userAgent: string;
serverUrl: string;
secretToken?: string;
apiKey?: string;
// ...additional transport options
}): WritableStream & EventEmitter
The primary intake transport. Construct one instance per agent lifecycle; it manages a persistent keepalive connection to APM Server, handles NDJSON serialization, gzip compression, and stream chopping. Use it when you need direct control over the APM intake stream rather than going through the high-level Agent facade.
import { CloudMetadata } from './apm-core/cloud-metadata/index.js';
class CloudMetadata {
constructor(
cloudProvider: 'auto' | 'aws' | 'gcp' | 'azure' | 'none',
logger: Logger,
serviceName: string
);
getCloudMetadata(callback: (err: Error | null, metadata: object | null) => void): void;
}
Probes cloud-provider IMDS endpoints with aggressive timeouts (100 ms socket connect, 1 s HTTP). Call getCloudMetadata once at agent startup to enrich every event with provider, region, instance ID, etc. Returns null when not running in a recognized cloud or when cloudProvider is 'none'.
import Metrics from './apm-core/metrics/index.js';
class Metrics {
constructor(agent: Agent);
start(refTimers: boolean): void;
stop(): void;
getOrCreateCounter(name: string, dimensions?: object): Counter | undefined;
getOrCreateGauge(name: string, collect: () => number, dimensions?: object): void;
getOrCreateHistogram(name: string, dimensions?: object): Histogram | undefined;
}
Wraps measured-reporting in an APM-aware registry. Call start(false) (unref timers) in serverless or CLI contexts so the process can exit naturally. Always call stop() on agent shutdown to flush final metric snapshots.
Boot the agent from source, passing config programmatically instead of via env vars. This is useful in monorepo setups where multiple services share one config loader.
import path from 'path';
// MUST be the very first import in the entry point
const Agent = require('./src/apm-core/agent');
const agent = new Agent();
agent.start({
serviceName: 'order-service',
serviceVersion: '2.1.0',
serverUrl: process.env.APM_SERVER_URL ?? 'http://localhost:8200',
secretToken: process.env.APM_SECRET_TOKEN,
environment: process.env.NODE_ENV ?? 'development',
logLevel: 'info',
captureBody: 'errors',
transactionSampleRate: 0.25,
});
// Agent is now active; subsequent requires are auto-instrumented
const express = require('express');
const app = express();
app.get('/health', (_req, res) => res.json({ status: 'ok' }));
app.listen(3000, () => console.log('listening'));
Enrich a custom metadata payload with cloud provider details before registering the service.
import { CloudMetadata } from './src/apm-core/cloud-metadata/index';
import pino from 'pino';
const logger = pino({ level: 'warn' });
const cloud = new CloudMetadata('auto', logger, 'inventory-service');
cloud.getCloudMetadata((err, metadata) => {
if (err) {
console.warn('Cloud metadata unavailable:', err.message);
} else {
console.log('Running on:', metadata);
// { provider: 'aws', region: 'us-east-1', instance: { id: 'i-0abc...' } }
}
// Continue application bootstrap
startApp();
});
function startApp() { /* ... */ }
Use the Metrics class to track a business event counter that will be flushed on the configured metricsInterval.
// Assumes `agent` is a started Agent instance from agent.js
import Metrics from './src/apm-core/metrics/index';
const metrics = new Metrics(agent);
metrics.start(false); // unref timers
const ordersCounter = metrics.getOrCreateCounter('orders.placed', {
region: 'eu-west-1',
});
function handleOrder(order: Order) {
processOrder(order);
ordersCounter?.inc();
}
process.on('SIGTERM', () => {
metrics.stop();
process.exit(0);
});
agent.js - Root Agent class; owns the lifecycle (start, destroy) and wires together instrumentation, metrics, cloud metadata, and the APM client.apm-client/ - HttpApmClient manages the TCP intake stream to APM Server; NoopApmClient is a silent drop replacement used when the agent is disabled.cloud-metadata/ - One module per provider (aws.js, azure.js, gcp.js) plus CallbackCoordination for racing concurrent probes with a global timeout.config/ - config.js reads all sources (env, options object, central config); schema.js declares every supported option; normalizers.js coerces types and validates values.filters/ - sanitize-field-names.js applies wildcard patterns to redact sensitive header/body field names before they leave the process.instrumentation/ - index.js sets up RITM/IITM hooks and owns the module patcher registry; transaction.js and span.js are the core trace-event models; run-context/ provides async context propagation via AsyncLocalStorage or AsyncHooks.metrics/ - index.js exports Metrics; registry.js wraps measured-reporting; queue.js creates Bull/BullMQ queue depth gauges.middleware/ - Express/Connect middleware that starts transactions from incoming HTTP requests.opentelemetry-bridge/ - Intercepts OTel API calls and routes them into APM spans, allowing OTel-instrumented libraries to appear in APM traces without a collector.opentelemetry-metrics/ - Registers an OTel SDK MetricReader that forwards measurements to the APM metrics pipeline.tracecontext/ - Parses and serializes W3C traceparent and tracestate headers for distributed tracing propagation.constants.js - Single source of truth for string literals shared across subsystems (e.g. CONTEXT_MANAGER_ASYNCHOOKS).errors.js - Captures Error objects, extracts stack frames, and normalizes them into APM error intake format.lambda.js - Detects the Lambda handler path from _HANDLER env var and wraps it for cold-start and invocation tracking.logging.js - Builds a pino logger with ECS formatting; exposes NoopLogger for test use.parsers.js - Extracts URL, method, headers, user-agent, and body context from Node.js IncomingMessage/ServerResponse pairs.stacktraces.js - Collects V8 stack frames, applies source-map translation, and culls internal frames.symbols.js - Exports a shared Symbol registry so instrumentation code and user code reference identical private property keys.wildcard-matcher.js - Implements the *-glob matching used by transactionIgnoreUrls, sanitizeFieldNames, and similar list-type config options.require/import the absolute first statement in your entry file, before Express, Knex, Redis, etc.--import: require-in-the-middle cannot hook ES module loads without the loader. Fix: add --import elastic-apm-node/start.js (or equivalent source path) to your node invocation.metricsInterval: 0 with Metrics.start(): The start method asserts metricsInterval > 0. Fix: guard with if (agent._conf.metricsInterval > 0) metrics.start(false).cloudProvider: 'none' or hardcode the provider if the deployment environment is known.HttpApmClient missing required options: The client throws if agentName, agentVersion, serviceName, or userAgent are absent. Fix: always supply all four requiredOpts even in custom/minimal configurations.tsconfig paths are compile-time only. Fix: add tsconfig-paths/register or use tsc-alias in the build step so runtime require resolves apm-core/* correctly.I have the Elastic APM Node.js agent core library source copied into `src/apm-core/`
in my project. The integration guide is in `USAGE.md` at the project root.
The upstream package is `user@example.com`.
Please help me integrate this APM source into my project step by step:
1. Read `USAGE.md` and `src/apm-core/agent.js` to understand the Agent API.
2. Install all required dependencies listed in USAGE.md § "Required dependencies".
3. Add agent bootstrap code at the top of my entry file (`src/index.ts`) using
the real `Agent` class from `src/apm-core/agent.js`. Use env vars for
`serverUrl`, `secretToken`, and `serviceName`.
4. Wire cloud metadata fetching using `CloudMetadata` from
`src/apm-core/cloud-metadata/index.js` so startup logs show the provider.
5. Add a custom counter metric using `Metrics` from `src/apm-core/metrics/index.js`
to track [describe your business event].
6. Ensure the agent is stopped cleanly on `SIGTERM`.
7. Show me the final diff. Do not invent any API methods; use only what is
documented in USAGE.md and visible in the source files under `src/apm-core/`.
The source is licensed under the BSD 2-Clause License (Elasticsearch B.V. and contributors). See source/LICENSE if present, or the license header in every source file. Upstream package: elastic-apm-node — source repository: github.com/elastic/apm-agent-nodejs.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费