{"id":13527609,"url":"https://github.com/keymetrics/pm2-io-apm","last_synced_at":"2025-05-14T19:08:53.955Z","repository":{"id":32459003,"uuid":"123687338","full_name":"keymetrics/pm2-io-apm","owner":"keymetrics","description":"PM2.io APM for Node.JS","archived":false,"fork":false,"pushed_at":"2024-11-13T12:20:49.000Z","size":1171,"stargazers_count":150,"open_issues_count":33,"forks_count":43,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-05-03T10:01:52.160Z","etag":null,"topics":["apm","logs","metrics","monitoring","nodejs","pm2","profiling","tracing"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/keymetrics.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-03-03T11:51:51.000Z","updated_at":"2025-03-10T01:39:05.000Z","dependencies_parsed_at":"2024-06-04T17:46:16.312Z","dependency_job_id":"1d438352-35b5-46b0-b4a0-e81926dae35c","html_url":"https://github.com/keymetrics/pm2-io-apm","commit_stats":{"total_commits":617,"total_committers":18,"mean_commits":34.27777777777778,"dds":0.5024311183144247,"last_synced_commit":"714ec396ca212e43e6129a6e2413b2be2c1b1aa1"},"previous_names":["keymetrics/pmx-2"],"tags_count":56,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keymetrics%2Fpm2-io-apm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keymetrics%2Fpm2-io-apm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keymetrics%2Fpm2-io-apm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keymetrics%2Fpm2-io-apm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/keymetrics","download_url":"https://codeload.github.com/keymetrics/pm2-io-apm/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254101588,"owners_count":22014907,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apm","logs","metrics","monitoring","nodejs","pm2","profiling","tracing"],"created_at":"2024-08-01T06:01:53.842Z","updated_at":"2025-05-14T19:08:52.405Z","avatar_url":"https://github.com/keymetrics.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"http://pm2.keymetrics.io\"\u003e\n    \u003cimg width=411px src=\"https://raw.githubusercontent.com/keymetrics/pm2-io-apm/master/pres/io-white.png\"\u003e\n  \u003c/a\u003e\n  \u003cbr/\u003e\n\n\u003cbr/\u003e\n\u003cbr/\u003e\n\u003c/div\u003e\n\n\nThe [@pm2/io](https://github.com/keymetrics/pm2-io-apm/tree/master/test) module comes along with PM2. It is the PM2 library responsible for gathering the metrics, reporting exceptions, exposing remote actions and every interaction with your application.\n\nYou can also use it as a standalone agent, if you want to connect your nodejs process to PM2 Enterprise but without having to launch your application with PM2.\n\n# Table of Contents\n\n- [**Installation**](https://github.com/keymetrics/pm2-io-apm/tree/master#installation)\n- [**Expose Custom Metrics**](https://github.com/keymetrics/pm2-io-apm/tree/master#expose-custom-metrics)\n- [**Expose Remote Actions**](https://github.com/keymetrics/pm2-io-apm#expose-remote-actions-trigger-functions-remotely)\n- [**Report Custom Errors**](https://github.com/keymetrics/pm2-io-apm#report-user-error)\n- [**Distributed Tracing**](https://github.com/keymetrics/pm2-io-apm#distributed-tracing)\n- [**Configuration**](https://github.com/keymetrics/pm2-io-apm/tree/master#configuration)\n- [**Migration Guide**](https://github.com/keymetrics/pm2-io-apm#migration-guides)\n- [**Development**](https://github.com/keymetrics/pm2-io-apm/tree/master#development)\n- [**Notes**](https://github.com/keymetrics/pm2-io-apm/tree/master#notes)\n\n\n# Installation\n\nWith npm:\n\n```bash\nnpm install @pm2/io --save\n```\n\nWith yarn:\n\n```bash\nyarn add @pm2/io\n```\n\n## V8 Runtime Metrics\n\nTo retrieve by default V8 Runtime metrics like:\n- V8 Garbage Collector metrics\n- [CPU Context Switch](https://unix.stackexchange.com/questions/442969/what-exactly-are-voluntary-context-switches)\n- [Page Fault](https://en.wikipedia.org/wiki/Page_fault#Types)\n\nInstall:\n\n```bash\nnpm install @pm2/node-runtime-stats\n```\n\nAnd restart the application.\n\n## Custom Metrics\n\n@pm2/io allows you to gather metrics from your code to be reported in the PM2 Plus/Enterprise dashboard.\n\n### Create a custom metrics\n\nYou can create a new custom metrics with the method `metric()` of `@pm2/io`.\n\n```javascript\nconst io = require('@pm2/io');\n\nconst users = io.metric({\n  name: 'Realtime user',\n});\nusers.set(10)\n```\n\nThis arguments are available:\n\n- **name**: The metric name (required; string)\n- **id**: The type of metric (default 'metric', string)\n- **unit**: unit of the measure (default ''; string)\n- **historic**: keep the history in PM2 Plus (default: true; boolean)\n\nThere are 4 different types of metrics:\n\n- **gauge**: To expose a variable's value\n- **counter**: A discrete counter to be triggered manually to count a number of occurrence\n- **meter**: To measure a frequency, a number of occurrences of a repeating event per unit of time\n- **histogram**: To measure a statistic, a statistic on a metric over the last 5 minutes\n\n### Metric: Variable Exposition\n\nThe first type of metric, called `metric`, allows to expose a variable's value. The variable can be exposed passively, with a function that gets called every second, or actively, with a method that you use to update the value.\n\n#### Active Mode\n\nIn active mode, you need to create a probe and call the method `set()` to update the value.\n\n```javascript\nconst myMetric = io.metric({\n  name: 'Realtime Value'\n});\n\nmyMetric.set(23);\n```\n\n#### Passive Mode\n\nIn passive mode you hust need to return the variable to be monitored:\n\n```javascript\nconst myMetric = io.metric({\n  name: 'Realtime Value',\n  value: () =\u003e {\n    return variable_to_monitor\n  }\n});\n```\n\n### Counter: Discrete Counter\n\nThe second type of metric, called `counter`, is a discrete counter that helps you count the number of occurrence of a particular event. The counter starts at 0 and can be incremented or decremented.\n\n```javascript\nconst io = require('@pm2/io');\n\nconst currentReq = io.counter({\n  name: 'Current req processed',\n  type: 'counter',\n});\n\nhttp.createServer((req, res) =\u003e {\n  // Increment the counter, counter will eq 1\n  currentReq.inc();\n  req.on('end', () =\u003e {\n    // Decrement the counter, counter will eq 0\n    currentReq.dec();\n  });\n});\n```\n\n### Meter: Frequency\n\nThe third type of metric, called `meter`, compute the frequency of an event. Each time the event happens, you need to call the `mark()` method. By default, the frequency is the number of events per second over the last minute.\n\n```javascript\nconst io = require('@pm2/io');\n\nconst reqsec = io.meter({\n  name: 'req/sec',\n  type: 'meter',\n});\n\nhttp.createServer((req, res) =\u003e {\n  reqsec.mark();\n  res.end({ success: true });\n});\n```\n\nAdditional options:\n- **samples**: (optional)(default: 1) Rate unit. Defaults to **1** sec.\n- **timeframe**: (optional)(default: 60) Timeframe over which the events will be analyzed. Defaults to **60** sec.\n\n### Histogram: Statistics\n\nCollect values and provide statistic tools to explore their distribution over the last 5 minutes.\n\n```javascript\nconst io = require('@pm2/io');\n\nconst latency = io.histogram({\n  name: 'latency',\n  measurement: 'mean'\n});\n\nvar latencyValue = 0;\n\nsetInterval(() =\u003e {\n  latencyValue = Math.round(Math.random() * 100);\n  latency.update(latencyValue);\n}, 100);\n```\n\nOptions are:\n- **measurement** : default: mean; min, max, sum, count, variance, mean, stddev, median, p75, p95, p99, p99.\n\n## Expose Remote Actions: Trigger Functions remotely\n\nRemotely trigger functions from PM2 Plus or Enterprise.\n\n### Simple actions\n\nThe function takes a function as a parameter (cb here) and need to be called once the job is finished.\n\nExample:\n\n```javascript\nconst io = require('@pm2/io');\n\nio.action('db:clean', (cb) =\u003e {\n  clean.db(() =\u003e {\n    // cb must be called at the end of the action\n    return cb({ success: true });\n  });\n});\n```\n\n## Report user error\n\nBy default, in the Issue tab, you are only alerted for uncaught exceptions. Any exception that you catch is not reported. You can manually report them with the `notifyError()` method.\n\n```javascript\nconst io = require('@pm2/io');\n\nio.notifyError(new Error('This is an error'), {\n  // you can some http context that will be reported in the UI\n  http: {\n    url: req.url\n  },\n  // or anything that you can like an user id\n  custom: {\n    user: req.user.id\n  }\n});\n```\n\n#### Express error reporting\n\nIf you want you can configure your express middleware to automatically send you an error with the error middleware of express :\n\n```javascript\nconst io = require('@pm2/io')\nconst express = require('express')\nconst app = express()\n\n// add the routes that you want\napp.use('/toto', () =\u003e {\n  throw new Error('ajdoijerr')\n})\n\n// always add the middleware as the last one\napp.use(io.expressErrorHandler())\n```\n\n#### Koa error reporting\n\nWe also expose a custom koa middleware to report error with a specific koa middleware :\n\n```javascript\nconst io = require('@pm2/io')\nconst Koa = require('koa')\nconst app = new Koa()\n\n// the order isn't important with koa\napp.use(pmx.koaErrorHandler())\n\n// add the routes that you want\napp.use(async ctx =\u003e {\n  ctx.throw(new Error('toto'))\n})\n```\n\n## Distributed Tracing\n\nThe Distributed Tracing allows to captures and propagates distributed traces through your system, allowing you to visualize how customer requests flow across services, rapidly perform deep root cause analysis, and better analyze latency across a highly distributed set of services.\nIf you want to enable it, here the simple options to enable:\n\n\n```javascript\nconst io = require('@pm2/io').init({\n  tracing: {\n    enabled: true,\n    // will add the actual queries made to database, false by default\n    detailedDatabasesCalls: true,\n    // if you want you can ignore some endpoint based on their path\n    ignoreIncomingPaths: [\n      // can be a regex\n      /misc/,\n      // or a exact string\n      '/api/bucket'\n      // or a function with the request\n      (url, request) =\u003e {\n        return true\n      }\n    ],\n    // same as above but used to match entire URLs\n    ignoreOutgoingUrls: [],\n    /**\n     * Determines the probability of a request to be traced. Ranges from 0.0 to 1.0\n     * default is 0.5\n     */\n    samplingRate: 0.5\n  }\n})\n```\n\nBy default we ignore specific incoming requests (you can override this by setting `ignoreIncomingPaths: []`):\n- Request with the OPTIONS or HEAD method\n- Request fetching a static ressources (`*.js`, `*.css`, `*.ico`, `*.svg`, `.png` or `*webpack*`)\n\n### What's get traced\n\nWhen your application will receive a request from either `http`, `https` or `http2` it will start a trace. After that, we will trace the following modules:\n - `http` outgoing requests\n - `https` outgoing requests\n - `http2` outgoing requests\n - `mongodb-core` version 1 - 3\n - `redis` versions \u003e 2.6\n - `ioredis` versions \u003e 2.6\n - `mysql` version 1 - 3\n - `mysql2` version 1 - 3\n - `pg` version \u003e 6\n - `vue-server-renderer` version 2\n\n### Custom Tracing API\n\nThe custom tracing API can be used to create custom trace spans. A span is a particular unit of work within a trace, such as an RPC request. Spans may be nested; the outermost span is called a root span, even if there are no nested child spans. Root spans typically correspond to incoming requests, while child spans typically correspond to outgoing requests, or other work that is triggered in response to incoming requests. This means that root spans shouldn't be created in a context where a root span already exists; a child span is more suitable here. Instead, root spans should be created to track work that happens outside of the request lifecycle entirely, such as periodically scheduled work. To illustrate:\n\n```js\nconst io = require('@pm2/io').init({ tracing: true })\nconst tracer = io.getTracer()\n// ...\n\napp.get('/:token', function (req, res) {\n  const token = req.params.token\n  // the '2' correspond to the type of operation you want to trace\n  // can be 0 (UNKNOWN), 1 (SERVER) or 2 (CLIENT)\n  // 'verifyToken' here will be the name of the operation\n  const customSpan = tracer.startChildSpan('verifyToken', 2)\n  // note that customSpan can be null if you are not inside a request\n  req.Token.verifyToken(token, (err, result) =\u003e {\n    if (err) {\n      // you can add tags to the span to attach more details to the span\n      customSpan.addAttribute('error', err.message)\n      customSpan.end()\n      return res.status(500).send('error')\n    }\n    customSpan.addAttribute('result', result)\n    // be sure to always .end() the spans\n    customSpan.end()\n    // redirect the user if the token is valid\n    res.send('/user/me')\n  })\n})\n\n// For any significant work done _outside_ of the request lifecycle, use\n// startRootSpan.\nconst traceOptions = {\n    name: 'my custom trace',\n    // the '1' correspond to the type of operation you want to trace\n    // can be 0 (UNKNOWN), 1 (SERVER) or 2 (CLIENT)\n    kind: '1'\n  }\nplugin.tracer.startRootSpan(traceOptions, rootSpan =\u003e {\n  // ...\n  // Be sure to call rootSpan.end().\n  rootSpan.end()\n});\n```\n\n## Configuration\n\n### Global configuration object\n\n```javascript\nexport class IOConfig {\n  /**\n   * Automatically catch unhandled errors\n   */\n  catchExceptions?: boolean = true\n  /**\n   * Configure the metrics to add automatically to your process\n   */\n  metrics?: {\n    eventLoop: boolean = true,\n    network: boolean = false,\n    http: boolean = true,\n    gc: boolean = true,\n    v8: boolean = true\n  }\n  /**\n   * Configure the default actions that you can run\n   */\n  actions?: {\n    eventLoopDump?: boolean = true\n  }\n  /**\n   * Configure availables profilers that will be exposed\n   */\n  profiling?: {\n    /**\n     * Toggle the CPU profiling actions\n     */\n    cpuJS: boolean = true\n    /**\n     * Toggle the heap snapshot actions\n     */\n    heapSnapshot: boolean = true\n    /**\n     * Toggle the heap sampling actions\n     */\n    heapSampling: boolean = true\n    /**\n     * Force a specific implementation of profiler\n     *\n     * available:\n     *  - 'addon' (using the v8-profiler-node8 addon)\n     *  - 'inspector' (using the \"inspector\" api from node core)\n     *  - 'none' (disable the profilers)\n     *  - 'both' (will try to use inspector and fallback on addon if available)\n     */\n    implementation: string = 'both'\n  }\n  /**\n   * Configure the transaction tracing options\n   */\n  tracing?: {\n    /**\n     * Enabled the distributed tracing feature.\n     */\n    enabled: boolean\n    /**\n     * If you want to report a specific service name\n     * the default is the same as in apmOptions\n     */\n    serviceName?: string\n    /**\n     * Generate trace for outgoing request that aren't connected to a incoming one\n     * default is false\n     */\n    outbound?: boolean\n    /**\n     * Determines the probability of a request to be traced. Ranges from 0.0 to 1.0\n     * default is 0.5\n     */\n    samplingRate?: number,\n    /**\n     * Add details about databases calls (redis, mongodb etc)\n     */\n    detailedDatabasesCalls?: boolean,\n    /**\n     * Ignore specific incoming request depending on their path\n     */\n    ignoreIncomingPaths?: Array\u003cIgnoreMatcher\u003chttpModule.IncomingMessage\u003e\u003e\n    /**\n     * Ignore specific outgoing request depending on their url\n     */\n    ignoreOutgoingUrls?: Array\u003cIgnoreMatcher\u003chttpModule.ClientRequest\u003e\u003e\n    /**\n     * Set to true when wanting to create span for raw TCP connection\n     * instead of new http request\n     */\n    createSpanWithNet: boolean\n  }\n  /**\n   * If you want to connect to PM2 Enterprise without using PM2, you should enable\n   * the standalone mode\n   *\n   * default is false\n   */\n  standalone?: boolean = false\n  /**\n   * Define custom options for the standalone mode\n   */\n  apmOptions?: {\n    /**\n     * public key of the bucket to which the agent need to connect\n     */\n    publicKey: string\n    /**\n     * Secret key of the bucket to which the agent need to connect\n     */\n    secretKey: string\n    /**\n     * The name of the application/service that will be reported to PM2 Enterprise\n     */\n    appName: string\n    /**\n     * The name of the server as reported in PM2 Enterprise\n     *\n     * default is os.hostname()\n     */\n    serverName?: string\n    /**\n     * Broadcast all the logs from your application to our backend\n     */\n    sendLogs?: Boolean\n    /**\n     * Avoid to broadcast any logs from your application to our backend\n     * Even if the sendLogs option set to false, you can still see some logs\n     * when going to the log interface (it automatically trigger broacasting log)\n     */\n    disableLogs?: Boolean\n    /**\n     * Since logs can be forwared to our backend you may want to ignore specific\n     * logs (containing sensitive data for example)\n     */\n    logFilter?: string | RegExp\n    /**\n     * Proxy URI to use when reaching internet\n     * Supporting socks5,http,https,pac,socks4\n     * see https://github.com/TooTallNate/node-proxy-agent\n     *\n     * example: socks5://username:password@some-socks-proxy.com:9050\n     */\n    proxy?: string\n  }\n}\n```\n\nYou can pass whatever options you want to `io.init`, it will automatically update its configuration.\n\n## Migration Guides\n\n### 2.x to 3.x\n\nHere the list of breaking changes :\n\n- Removed `io.scopedAction` because of low user adoption\n- Removed `io.notify` in favor of `io.notifyError` (droppin replacement)\n- Removed support for `gc-stats` module\n- Removed Heap profiling support when using the profiler addon (which wasn't possible at all)\n- Removed deep-metrics support (the module that allowed to get metrics about websocket/mongo out of the box), we are working on a better solution.\n- Removed `io.transpose`\n- Removed `io.probe()` to init metrics\n- **Changed the configuration structure**\n\nHigh chance that if you used a custom configuration for `io.init`, you need to change it to reflect the new configuration.\nApart from that and the `io.notify` removal, it shouldn't break the way you instanciated metrics.\nIf you find something else that breaks please report it to us (tech@keymetrics.io).\n\n### 3.x to 4.x\n\nThe only difference with the 4.x version is the new tracing system put in place, so the only changs are related to it:\n\n- **Dropped the support for node 4** (you can still use the 3.x if you use node 4 but you will not have access to the distributed tracing)\n- **Changed the tracing configuration** (see options above)\n\n## Development\n\nTo auto rebuild on file change:\n\n```bash\n$ npm install\n$ npm run watch\n```\n\nTo test only one file:\n\n```bash\n$ npm run unit \u003ctypescript-file-to-test.ts\u003e\n```\n\nRun transpilation + test + coverage:\n\n```bash\n$ npm run test\n```\n\nRun transpilation + test only:\n\n```bash\n$ npm run unit \u003ctest\u003e\n```\n\n## Notes\n\nCurently this package isn't compatible with `amqp` if you use the `network` metrics. We recommend to disable the metrics with the following configuration in this case :\n\n```javascript\nio.init({\n  metrics: {\n    network: false\n  }\n})\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkeymetrics%2Fpm2-io-apm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkeymetrics%2Fpm2-io-apm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkeymetrics%2Fpm2-io-apm/lists"}