{"id":13455735,"url":"https://github.com/gajus/roarr","last_synced_at":"2026-01-17T01:56:35.380Z","repository":{"id":39953858,"uuid":"105390095","full_name":"gajus/roarr","owner":"gajus","description":"JSON logger for Node.js and browser.","archived":false,"fork":false,"pushed_at":"2025-10-26T03:51:17.000Z","size":1063,"stargazers_count":1129,"open_issues_count":16,"forks_count":38,"subscribers_count":6,"default_branch":"main","last_synced_at":"2026-01-04T12:23:06.729Z","etag":null,"topics":["debugging","json","logger"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gajus.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"gajus","patreon":"gajus"}},"created_at":"2017-09-30T18:08:56.000Z","updated_at":"2026-01-03T01:48:49.000Z","dependencies_parsed_at":"2022-07-15T09:00:48.375Z","dependency_job_id":"4a901aef-36f0-4661-836e-868b1dbfa5a5","html_url":"https://github.com/gajus/roarr","commit_stats":{"total_commits":339,"total_committers":6,"mean_commits":56.5,"dds":"0.026548672566371723","last_synced_commit":"37dbe58b5cc4273e7ddf8982035b7a860589b326"},"previous_names":[],"tags_count":152,"template":false,"template_full_name":null,"purl":"pkg:github/gajus/roarr","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Froarr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Froarr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Froarr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Froarr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gajus","download_url":"https://codeload.github.com/gajus/roarr/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Froarr/sbom","scorecard":{"id":417368,"data":{"date":"2025-08-11","repo":{"name":"github.com/gajus/roarr","commit":"e170c9a1e3a249b4040146378f92e3d09e56deb4"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":2.9,"checks":[{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Code-Review","score":0,"reason":"Found 1/29 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/feature.yaml:1","Warn: no topLevel permission defined: .github/workflows/main.yaml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Pinned-Dependencies","score":3,"reason":"dependency not pinned by hash detected -- score normalized to 3","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/feature.yaml:8: update your workflow using https://app.stepsecurity.io/secureworkflow/gajus/roarr/feature.yaml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/feature.yaml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/gajus/roarr/feature.yaml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yaml:8: update your workflow using https://app.stepsecurity.io/secureworkflow/gajus/roarr/main.yaml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yaml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/gajus/roarr/main.yaml/main?enable=pin","Info:   0 out of   4 GitHub-owned GitHubAction dependencies pinned","Info:   2 out of   2 npmCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 2 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":0,"reason":"29 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-968p-4wvh-cqc8","Warn: Project is vulnerable to: GHSA-h5c3-5r3r-rr8q","Warn: Project is vulnerable to: GHSA-rmvr-2pp2-xj38","Warn: Project is vulnerable to: GHSA-xx4v-prfh-6cgc","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw","Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg","Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275","Warn: Project is vulnerable to: GHSA-f6v4-cf5j-vf3w","Warn: Project is vulnerable to: GHSA-67mh-4wv8-2f99","Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22","Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp","Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv","Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55","Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j","Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm","Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw","Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36","Warn: Project is vulnerable to: GHSA-92r3-m2mg-pj97","Warn: Project is vulnerable to: GHSA-c24v-8rfc-w8vw","Warn: Project is vulnerable to: GHSA-8jhw-289h-jh2g","Warn: Project is vulnerable to: GHSA-64vr-g452-qvp3","Warn: Project is vulnerable to: GHSA-9cwx-2883-4wfx","Warn: Project is vulnerable to: GHSA-vg6x-rcgg-rjx6","Warn: Project is vulnerable to: GHSA-x574-m823-4x7w","Warn: Project is vulnerable to: GHSA-4r4m-qw57-chr8","Warn: Project is vulnerable to: GHSA-xcj6-pq6g-qj4x","Warn: Project is vulnerable to: GHSA-356w-63v5-8wf4","Warn: Project is vulnerable to: GHSA-859w-5945-r5v3","Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-19T00:15:49.868Z","repository_id":39953858,"created_at":"2025-08-19T00:15:49.868Z","updated_at":"2025-08-19T00:15:49.868Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28213627,"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","status":"online","status_checked_at":"2026-01-05T02:00:06.358Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["debugging","json","logger"],"created_at":"2024-07-31T08:01:10.184Z","updated_at":"2026-01-17T01:56:35.355Z","avatar_url":"https://github.com/gajus.png","language":"TypeScript","readme":"# Roarr\n\n[![NPM version](http://img.shields.io/npm/v/roarr.svg?style=flat-square)](https://www.npmjs.org/package/roarr)\n[![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical)\n[![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social\u0026label=Follow)](https://twitter.com/kuizinas)\n\nJSON logger for Node.js and browser.\n\n## Motivation\n\nFor a long time I have been a big fan of using [`debug`](https://github.com/visionmedia/debug). `debug` is simple to use, works in Node.js and browser, does not require configuration and it is fast. However, problems arise when you need to parse logs. Anything but one-line text messages cannot be parsed in a safe way.\n\nTo log structured data, I have been using [Winston](https://github.com/winstonjs/winston) and [Bunyan](https://github.com/trentm/node-bunyan). These packages are great for application-level logging. I have preferred Bunyan because of the [Bunyan CLI program](https://github.com/trentm/node-bunyan#cli-usage) used to pretty-print logs. However, these packages require program-level configuration – when constructing an instance of a logger, you need to define the transport and the log-level. This makes them unsuitable for use in code designed to be consumed by other applications.\n\nThen there is [pino](https://github.com/pinojs/pino). pino is fast JSON logger, it has CLI program equivalent to Bunyan, it decouples transports, and it has sane default configuration. Unfortunately, you still need to instantiate logger instance at the application-level. This makes it more suitable for application-level logging just like Winston and Bunyan.\n\nI needed a logger that:\n\n* Does not block the event cycle (=fast).\n* Does not require initialization.\n* Produces structured data.\n* [Decouples transports](#transports).\n* Has a [CLI program](#cli-program).\n* Works in Node.js and browser.\n* Configurable using environment variables.\n\nIn other words,\n\n* a logger that I can use in an application code and in dependencies.\n* a logger that allows to correlate logs between the main application code and the dependency code.\n* a logger that works well with transports in external processes.\n\nRoarr is this logger.\n\n## Usage\n\n### Producing logs\n\nRoarr logger API for producing logs is the same in Node.js and browser.\n\n1. Import `roarr`\n2. Use any of the [API](#api) methods to log messages.\n\nExample:\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\n\nlog('foo');\n```\n\n### Consuming logs\n\nRoarr logs are consumed differently in Node.js and browser.\n\n#### Node.js\n\nIn Node.js, Roarr logging is disabled by default. To enable logging, you must start program with an environment variable `ROARR_LOG` set to `true`, e.g.\n\n```bash\nROARR_LOG=true node ./index.js\n```\n\nAll logs will be written to stdout.\n\n#### Browser\n\nIn a browser, you must implement `ROARR.write` method to read logs, e.g.\n\n```ts\nimport {\n  ROARR,\n} from 'roarr';\n\nROARR.write = () =\u003e {};\n```\n\nThe API of the `ROARR.write` is:\n\n```ts\n(message: string) =\u003e void;\n```\n\nExample implementation:\n\n```ts\nimport {\n  ROARR,\n} from 'roarr';\n\nROARR.write = (message) =\u003e {\n  console.log(JSON.parse(message));\n};\n```\n\nor if you are initializing `ROARR.write` _before_ `roarr` is loaded:\n\n```ts\n// Ensure that `globalThis.ROARR` is configured.\nconst ROARR = globalThis.ROARR = globalThis.ROARR || {};\n\nROARR.write = (message) =\u003e {\n  console.log(JSON.parse(message));\n};\n```\n\nIf your platform does not support [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), use [`globalthis` polyfill](https://www.npmjs.com/package/globalthis).\n\nYou may also use [`@roarr/browser-log-writer`](https://github.com/gajus/roarr-browser-log-writer) that implements and opinionated browser logger with [Liqe](https://github.com/gajus/liqe) query support for filtering logs.\n\n### Filtering logs\n\n#### Node.js\n\nIn Node.js, Roarr prints all or none logs (refer to the [`ROARR_LOG` environment variable](#environment-variables) documentation).\n\nUse [`@roarr/cli` program](https://github.com/gajus/roarr-cli#filtering-logs) to filter logs, e.g.\n\n```bash\nROARR_LOG=true node ./index.js | roarr --filter 'context.logLevel:\u003e30'\n```\n\n#### Browser\n\nIn a browser, Roarr calls `globalThis.ROARR.write` for every log message. Implement your own custom logic to filter logs, e.g.\n\n```ts\nglobalThis.ROARR.write = (message) =\u003e {\n  const payload = JSON.parse(message);\n\n  if (payload.context.logLevel \u003e 30) {\n    console.log(payload);\n  }\n};\n```\n\n## Log message format\n\n|Property name|Contents|\n|---|---|\n|`context`|Arbitrary, user-provided structured data. See [context property names](#context-property-names).|\n|`message`|User-provided message formatted using [printf](https://en.wikipedia.org/wiki/Printf_format_string).|\n|`sequence`|Incremental sequence ID (see [`adopt`](#adopt) for description of the format and its meaning).|\n|`time`|Unix timestamp in milliseconds.|\n|`version`|Roarr log message format version.|\n\nExample:\n\n```json\n{\n  \"context\": {\n    \"application\": \"task-runner\",\n    \"hostname\": \"curiosity.local\",\n    \"instanceId\": \"01BVBK4ZJQ182ZWF6FK4EC8FEY\",\n    \"taskId\": 1\n  },\n  \"message\": \"starting task ID 1\",\n  \"sequence\": \"0\",\n  \"time\": 1506776210000,\n  \"version\": \"1.0.0\"\n}\n```\n\n## API\n\n`roarr` package exports a function with the following API:\n\n```ts\nexport type Logger =\n  (\n    context: MessageContext,\n    message: string,\n    c?: SprintfArgument,\n    d?: SprintfArgument,\n    e?: SprintfArgument,\n    f?: SprintfArgument,\n    g?: SprintfArgument,\n    h?: SprintfArgument,\n    i?: SprintfArgument,\n    k?: SprintfArgument\n  ) =\u003e void |\n  (\n    message: string,\n    b?: SprintfArgument,\n    c?: SprintfArgument,\n    d?: SprintfArgument,\n    e?: SprintfArgument,\n    f?: SprintfArgument,\n    g?: SprintfArgument,\n    h?: SprintfArgument,\n    i?: SprintfArgument,\n    k?: SprintfArgument\n  ) =\u003e void;\n```\n\nTo put it into words:\n\n* First parameter can be either a string (message) or an object.\n  * If first parameter is an object (context), the second parameter must be a string (message).\n* Arguments after the message parameter are used to enable [printf message formatting](https://en.wikipedia.org/wiki/Printf_format_string).\n  * Printf arguments must be of a primitive type (`string | number | boolean | null`).\n  * There can be up to 9 printf arguments (or 8 if the first parameter is the context object).\n\nRefer to the [Usage documentation](#usage) for common usage examples.\n\n### `adopt`\n\n```ts\n\u003cT\u003e(routine: () =\u003e Promise\u003cT\u003e, context: MessageContext | TransformMessageFunction\u003cMessageContext\u003e) =\u003e Promise\u003cT\u003e,\n```\n\n`adopt` function uses Node.js [`async_context`](https://nodejs.org/api/async_context.html) to pass-down context properties.\n\nWhen using `adopt`, context properties will be added to all _all_ Roarr messages within the same asynchronous context, e.g.\n\n```ts\nlog.adopt(\n  () =\u003e {\n    log('foo 0');\n\n    log.adopt(\n      () =\u003e {\n        log('foo 1');\n      },\n      {\n        baz: 'baz 1',\n      },\n    );\n  },\n  {\n    bar: 'bar 0',\n  },\n);\n```\n\n```json\n{\"context\":{\"bar\":\"bar 0\"},\"message\":\"foo 0\",\"sequence\":\"0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"bar\":\"bar 0\",\"baz\":\"baz 1\"},\"message\":\"foo 1\",\"sequence\":\"0.0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n```\n\n#### `sequence` value\n\n`sequence` represents async context hierarchy in [`ltree`](https://www.postgresql.org/docs/current/ltree.html) format, i.e.\n\n```xml\n\u003ctop-level sequential invocation ID\u003e[.\u003casync operation sequential invocation ID\u003e]\n```\n\nMembers of sequence value represent log index relative to the async execution context. This information can be used to establish the origin of the log invocation in an asynchronous context, e.g.\n\n```ts\nlog.adopt(() =\u003e {\n  log('foo 0');\n  log.adopt(() =\u003e {\n    log('bar 0');\n    log.adopt(() =\u003e {\n      log('baz 0');\n      setTimeout(() =\u003e {\n        log('baz 1');\n      }, 10);\n    });\n    log('bar 1');\n  });\n});\n```\n\n```json\n{\"context\":{},\"message\":\"foo 0\",\"sequence\":\"0.0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{},\"message\":\"bar 0\",\"sequence\":\"0.1.0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{},\"message\":\"baz 0\",\"sequence\":\"0.1.1.0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{},\"message\":\"bar 1\",\"sequence\":\"0.1.2\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{},\"message\":\"baz 1\",\"sequence\":\"0.1.1.1\",\"time\":1506776210010,\"version\":\"2.0.0\"}\n```\n\nNotice that even though logs `baz 0` and `baz 1` were produced at different times, you can tell that one was produced after another by looking at their sequence values `0.1.1.0` and `0.1.1.1`.\n\n#### Requirements\n\n* `adopt` method only works in Node.js.\n\n### `child`\n\nThe `child` function has two signatures:\n\n1. Accepts an object.\n2. Accepts a function.\n\n#### Object parameter\n\n```ts\n(context: MessageContext): Logger,\n```\n\nCreates a child logger that appends child `context` to every subsequent message.\n\nExample:\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\n\nconst barLog = log.child({\n  foo: 'bar'\n});\n\nlog.debug('foo 1');\n\nbarLog.debug('foo 2');\n```\n\n```json\n{\"context\":{\"logLevel\":20},\"message\":\"foo 1\",\"sequence\":\"0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"foo\":\"bar\",\"logLevel\":20},\"message\":\"foo 2\",\"sequence\":\"1\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n```\n\n#### Function parameter\n\n```ts\n\u003cT\u003e(context: TransformMessageFunction\u003cMessageContext\u003cT\u003e\u003e): Logger\u003cT\u003e\n```\n\nCreates a child logger that translates every subsequent message.\n\nExample:\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\n\nconst barLog = log.child\u003c{error: Error}\u003e((message) =\u003e {\n  return {\n    ...message,\n    context: {\n      ...message.context,\n      ...message.context.error \u0026\u0026 {\n        error: {\n          message: message.context.error.message,\n        },\n      },\n    },\n  };\n});\n\nlog.debug('foo 1');\n\nbarLog.debug({\n  error: new Error('bar'),\n}, 'foo 2');\n```\n\n```json\n{\"context\":{\"logLevel\":20},\"message\":\"foo 1\",\"sequence\":\"0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":20,\"error\":{\"message\":\"bar\"}},\"message\":\"bar 2\",\"sequence\":\"1\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n```\n\nA typical use case for this pattern is serialization (e.g. of HTTP request, response or error object) and redaction of sensitive data from logs.\n\n### `getContext`\n\nReturns the current context.\n\nExample:\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\n\nconst childLogger = log.child({\n  foo: 'bar'\n});\n\nchildLogger.getContext();\n\n// {foo: 'bar'}\n```\n\n### `trace`\n### `debug`\n### `info`\n### `warn`\n### `error`\n### `fatal`\n\nConvenience methods for logging a message with `logLevel` context property value set to a numeric value representing the [log level](#log-levels), e.g.\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\n\nlog.trace('foo');\nlog.debug('foo');\nlog.info('foo');\nlog.warn('foo');\nlog.error('foo');\nlog.fatal('foo');\n```\n\nProduces output:\n\n```json\n{\"context\":{\"logLevel\":10},\"message\":\"foo\",\"sequence\":\"0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":20},\"message\":\"foo\",\"sequence\":\"1\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":30},\"message\":\"foo\",\"sequence\":\"2\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":40},\"message\":\"foo\",\"sequence\":\"3\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":50},\"message\":\"foo\",\"sequence\":\"4\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":60},\"message\":\"foo\",\"sequence\":\"5\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n```\n\n### `traceOnce`\n### `debugOnce`\n### `infoOnce`\n### `warnOnce`\n### `errorOnce`\n### `fatalOnce`\n\nJust like the regular logger methods, but logs the message only once.\n\nNote: Internally, Roarr keeps a record of the last 1,000 `Once` invocations. If this buffer overflows, then the message is going to be logged again until the next time the buffer overflows again. \n\n## Utilities\n\n### `getLogLevelName`\n\nProvides log level name (trace, debug, ...) for a numeric log level (10, 20, ...).\n\nIf numeric log level is between two ranges, then resolves to the one with greater severity (e.g. 5 =\u003e trace).\n\nIf numeric log level is greater than the maximum supported, then falls back to the greatest severity (fatal).\n\n```ts\nimport {\n  getLogLevelName,\n} from 'roarr';\nimport type {\n  LogLevelName,\n} from 'roarr';\n\ngetLogLevelName(numericLogLevel: number): LogLevelName;\n```\n\n## Middlewares\n\nRoarr logger supports middlewares implemented as [`child`](#child) message translate functions, e.g.\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\nimport createSerializeErrorMiddleware from '@roarr/middleware-serialize-error';\n\nconst childLog = log.child(createSerializeErrorMiddleware());\n\nconst error = new Error('foo');\n\nlog.debug({error}, 'bar');\nchildLog.debug({error}, 'bar');\n```\n\n```json\n{\"context\":{\"logLevel\":20,\"error\":{}},\"message\":\"bar\",\"sequence\":\"0\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n{\"context\":{\"logLevel\":20,\"error\":{\"name\":\"Error\",\"message\":\"foo\",\"stack\":\"[REDACTED]\"}},\"message\":\"bar\",\"sequence\":\"1\",\"time\":1506776210000,\"version\":\"2.0.0\"}\n```\n\nRoarr middlewares enable translation of every bit of information that is used to construct a log message.\n\nThe following are the official middlewares:\n\n* [`@roarr/middleware-serialize-error`](https://github.com/gajus/roarr-middleware-serialize-error)\n\nRaise an issue to add your middleware of your own creation.\n\n## CLI program\n\nRoarr CLI program provides ability to filter and pretty-print Roarr logs.\n\n![CLI output demo](./.README/cli-output-demo.png)\n\nCLI program has been moved to a separate package [`@roarr/cli`](https://github.com/gajus/roarr-cli).\n\n```bash\nnpm install @roarr/cli -g\n```\n\nExplore all CLI commands and options using `roarr --help` or refer to [`@roarr/cli`](https://github.com/gajus/roarr-cli) documentation.\n\n## Transports\n\nA transport in most logging libraries is something that runs in-process to perform some operation with the finalized log line. For example, a transport might send the log line to a standard syslog server after processing the log line and reformatting it.\n\nRoarr does not support in-process transports.\n\nRoarr does not support in-process transports because Node processes are single threaded processes (ignoring some technical details). Given this restriction, Roarr purposefully offloads handling of the logs to external processes so that the threading capabilities of the OS can be used (or other CPUs).\n\nDepending on your configuration, consider one of the following log transports:\n\n* [Beats](https://www.elastic.co/products/beats) for aggregating at a process level (written in Go).\n* [logagent](https://github.com/sematext/logagent-js) for aggregating at a process level (written in JavaScript).\n* [Fluentd](https://www.fluentd.org/) for aggregating logs at a container orchestration level (e.g. Kubernetes) (written in Ruby).\n\n## Node.js environment variables\n\nUse environment variables to control `roarr` behavior.\n\n|Name||Function|Default|\n|---|---|---|---|\n|`ROARR_LOG`|Boolean|Enables/ disables logging.|`false`|\n|`ROARR_STREAM`|`STDOUT`, `STDERR`|Name of the stream where the logs will be written.|`STDOUT`|\n\nWhen using `ROARR_STREAM=STDERR`, use [`3\u003e\u00261 1\u003e\u00262 2\u003e\u00263 3\u003e\u0026-`](https://stackoverflow.com/a/2381643/368691) to pipe stderr output.\n\n## Conventions\n\n### Context property names\n\nRoarr does not have reserved context property names. However, I encourage use of the following conventions:\n\n|Context property name|Use case|\n|---|---|\n|`application`|Name of the application (do not use in code intended for distribution; see `package` property instead).|\n|`logLevel`|A numeric value indicating the [log level](#log-levels). See [API](#api) for the build-in loggers with a pre-set log-level.|\n|`namespace`|Namespace within a package, e.g. function name. Treat the same way that you would construct namespaces when using the [`debug`](https://github.com/visionmedia/debug) package.|\n|`package`|Name of the NPM package.|\n\nThe `roarr pretty-print` [CLI program](#cli-program) is using the context property names suggested in the conventions to pretty-print the logs for the developer inspection purposes.\n\n#### Log levels\n\nThe `roarr pretty-print` [CLI program](#cli-program) translates `logLevel` values to the following human-readable names:\n\n|`logLevel`|Human-readable name|\n|---|---|\n|10|TRACE|\n|20|DEBUG|\n|30|INFO|\n|40|WARN|\n|50|ERROR|\n|60|FATAL|\n\n### Using Roarr in an application\n\nTo avoid code duplication, you can use a singleton pattern to export a logger instance with predefined context properties (e.g. describing the application).\n\nI recommend to create a file `Logger.js` in the project directory. Inside this file create and export a child instance of Roarr with context parameters describing the project and the script instance, e.g.\n\n```ts\n/**\n * @file Example contents of a Logger.js file.\n */\n\nimport {\n  Roarr,\n} from 'roarr';\n\nexport const Logger = Roarr.child({\n  // .foo property is going to appear only in the logs that are created using\n  // the current instance of a Roarr logger.\n  foo: 'bar'\n});\n```\n\nRoarr does not have reserved context property names. However, I encourage use of the [conventions](#conventions).\n\n## Recipes\n\n### Overriding message serializer\n\nRoarr is opinionated about how it serializes (converts objects to JSON string) log messages, e.g. in Node.js it uses a schema based serializer, which is very fast, but does not allow custom top-level properties.\n\nYou can override this serializer by defining `ROARR.serializeMessage`:\n\n```ts\nimport type {\n  MessageSerializer,\n} from 'roarr';\n\nconst ROARR = globalThis.ROARR = globalThis.ROARR || {};\n\nconst serializeMessage: MessageSerializer = (message) =\u003e {\n  return JSON.stringify(message);\n};\n\nROARR.serializeMessage = serializeMessage;\n```\n\n### Logging errors\n\nThis is not specific to Roarr – this suggestion applies to any kind of logging.\n\nIf you want to include an instance of [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) in the context, you must serialize the error.\n\nThe least-error prone way to do this is to use an existing library, e.g. [`serialize-error`](https://www.npmjs.com/package/serialize-error).\n\n```ts\nimport {\n  Roarr as log,\n} from 'roarr';\nimport serializeError from 'serialize-error';\n\n// [..]\n\nsend((error, result) =\u003e {\n  if (error) {\n    log.error({\n      error: serializeError(error)\n    }, 'message not sent due to a remote error');\n\n    return;\n  }\n\n  // [..]\n});\n```\n\nWithout using serialization, your errors will be logged without the error name and stack trace.\n\n## Anti-patterns\n\n### Overriding `globalThis.ROARR.write` in Node.js\n\nOverriding `globalThis.ROARR.write` in Node.js works the same way as it does in [browser](#browser). However, overriding `ROARR.write` in Node.js is considered an anti-pattern because it defeats some of the major benefits outlined in [Motivation](https://github.com/gajus/roarr#motivation) section of the documentation. Namely, by overriding `ROARR.write` in Node.js you are adding blocking events to the event cycle and coupling application logic with log handling logic.\n\nIf you have a use case that asks for overriding `ROARR.write` in Node.js, then [raise an issue](https://github.com/gajus/roarr/issues) to discuss your requirements.\n\n## Integrations\n\n### Using with Sentry\n\nhttps://github.com/gajus/roarr-sentry\n\n### Using with Fastify\n\nhttps://github.com/gajus/roarr-fastify\n\n### Using with Elasticsearch\n\nIf you are using [Elasticsearch](https://www.elastic.co/products/elasticsearch), you will want to create an [index template](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html).\n\nThe following serves as the ground work for the index template. It includes the main Roarr log message properties (context, message, time) and the context properties suggested in the [conventions](#conventions).\n\n```json\n{\n  \"mappings\": {\n    \"log_message\": {\n      \"_source\": {\n        \"enabled\": true\n      },\n      \"dynamic\": \"strict\",\n      \"properties\": {\n        \"context\": {\n          \"dynamic\": true,\n          \"properties\": {\n            \"application\": {\n              \"type\": \"keyword\"\n            },\n            \"hostname\": {\n              \"type\": \"keyword\"\n            },\n            \"instanceId\": {\n              \"type\": \"keyword\"\n            },\n            \"logLevel\": {\n              \"type\": \"integer\"\n            },\n            \"namespace\": {\n              \"type\": \"text\"\n            },\n            \"package\": {\n              \"type\": \"text\"\n            }\n          }\n        },\n        \"message\": {\n          \"type\": \"text\"\n        },\n        \"time\": {\n          \"format\": \"epoch_millis\",\n          \"type\": \"date\"\n        }\n      }\n    }\n  },\n  \"template\": \"logstash-*\"\n}\n```\n\n### Using with Scalyr\n\nIf you are using [Scalyr](https://www.scalyr.com/), you will want to create a custom parser `RoarrLogger`:\n\n```ts\n{\n  patterns: {\n    tsPattern: \"\\\\w{3},\\\\s\\\\d{2}\\\\s\\\\w{3}\\\\s\\\\d{4}\\\\s[\\\\d:]+\",\n    tsPattern_8601: \"\\\\d{4}-\\\\d{2}-\\\\d{2}T[\\\\d:.]+Z\"\n  }\n  formats: [\n    {format: \"${parse=json}$\"},\n    {format: \".*\\\"time\\\":$timestamp=number$,.*\"},\n    {format: \"$timestamp=tsPattern$ GMT $detail$\"},\n    {format: \"$timestamp=tsPattern_8601$ $detail$\"}\n  ]\n}\n```\n\nand configure the individual programs to use `RoarrLogger`. In case of Kubernetes, this means adding a `log.config.scalyr.com/attributes.parser: RoarrLogger` annotation to the associated deployment, pod or container.\n\n### Using with NestJS\n\nIf you are using [NestJS](https://docs.nestjs.com/), you can use [`nestjs-logger-roarr`](https://www.npmjs.com/package/nestjs-logger-roarr) to perform logging inside your application.\n\nTo enable one shared logger for the entire application:\n\n```typescript\nimport { RoarrLoggerService } from nestjs-logger-roarr';\nimport { AppModule } from \"app.module\";\n\nconst logger = RoarrLoggerService.sharedInstance();\nconst app = await NestFactory.create(AppModule, { logger });\n```\n\nTo enable mutiple injected loggers via the usual Module syntax:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config;\nimport { RoarrLoggerModule } from 'nestjs-logger-roarr';\n\n@Module({\n  imports: [\n    RoarrLoggerModule.forRoot({\n      logLevel: 'warn', // this is the *minimum* log level that will be displayed\n    }),\n  ]\n})\n\nexport class AppModule {}\n```\n\n## Documenting use of Roarr\n\nIf your package is using Roarr, include instructions in `README.md` describing how to enable logging, e.g.\n\n```md\n## Logging\n\nThis project uses [`roarr`](https://www.npmjs.com/package/roarr) logger to log the program's state.\n\nExport `ROARR_LOG=true` environment variable to enable log printing to `stdout`.\n\nUse [`roarr-cli`](https://github.com/gajus/roarr-cli) program to pretty-print the logs.\n```\n\n## Context Truncation\n\nRoarr by default truncates context properties if the context object is wider or deeper than 10 properties. At the moment, this is a hard-coded value. Waiting for feedback on whether this is a reasonable default and if it needs to be configurable.\n\nWhen the context goes over this limit, you will start seeing `...` entries in your logs, e.g.\n\n```json\n{\"a\":\"a\",\"b\":\"b\",\"c\":\"c\",\"d\":\"d\",\"e\":\"e\",\"f\":\"f\",\"g\":\"g\",\"h\":\"h\",\"i\":\"i\",\"j\":\"j\",\"...\":\"1 item not stringified\"}\n```\n\nThe reason for this is to prevent accidental logging of massive objects that can cause context truncation and performance issues.\n\n## Developing\n\nEvery time a change is made to the logger, one must update `ROARR_VERSION` value in [`./src/config.ts`](./src/config.ts).\n\nUnfortunately, this process cannot be automated because the version number is not known before `semantic-version` is called.\n","funding_links":["https://github.com/sponsors/gajus","https://patreon.com/gajus"],"categories":["Repository","Packages","TypeScript"],"sub_categories":["Logging"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgajus%2Froarr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgajus%2Froarr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgajus%2Froarr/lists"}