[
  {
    "path": ".babelrc",
    "content": "{\n  \"presets\": [\"@babel/preset-env\"]\n}\n"
  },
  {
    "path": ".editorconfig",
    "content": "# EditorConfig is awesome: https://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n# default configuration\n[*]\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nindent_style = space\nindent_size = 2\n\n# Tab indentation (no size specified)\n[Makefile]\nindent_style = tab\n"
  },
  {
    "path": ".eslintrc",
    "content": "{\n  \"env\": {\n    \"jest\": true,\n  },\n  \"extends\": \"@dabh/eslint-config-populist\",\n  \"rules\": {\n    \"one-var\": [\"error\", { \"var\": \"never\", \"let\": \"never\", \"const\": \"never\" }],\n    \"strict\": 0\n  },\n  \"parserOptions\": {\n    \"ecmaVersion\": 2022,\n  },\n}\n"
  },
  {
    "path": ".gitattributes",
    "content": "package-lock.json binary\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "content": "name: Have you encountered an issue?\ndescription: Report an issue with Winston.\ntitle: \"[Bug]: \"\nlabels: [\"Bug\", \"Needs Investigation\"]\nbody:\n  - type: markdown # Form Header\n    attributes:\n      value: >-\n        This issue form is for reporting bugs only!\n  - type: input # Search Terms\n    validations:\n      required: true\n    attributes:\n      label: 🔎 Search Terms\n      description: >-\n        What search terms did you use when trying to find an existing bug report, looking in both open and closed issues?\n        List them here (comma seperated) so people in the future can find this one more easily.\n  - type: textarea # Problem Definition\n    validations:\n      required: true\n    attributes:\n      label: The problem\n      description: >-\n        Please provide a clear and concise description of the problem you've encountered and what the\n        expected behavior was.\n  - type: markdown # Environment Section Header\n    attributes:\n      value: |\n        ## Environment\n  - type: input # Affected Version Input\n    id: winston-version\n    validations:\n      required: true\n    attributes:\n      label: What version of Winston presents the issue?\n      placeholder: v3.4.0\n      description: >\n        Can be found by running one of the following (depending on your package manager of choice):\n        - `npm list winston`\n        - `yarn list --pattern winston`\n  - type: input # Affected Version Input\n    id: node-version\n    validations:\n      required: true\n    attributes:\n      label: What version of Node are you using?\n      placeholder: v16.8.0\n      description: >\n        Can be found by running the following: `node -v`\n  - type: input # Last Known Working Version\n    attributes:\n      label: If this worked in a previous version of Winston, which was it?\n      placeholder: v3.0.0\n      description: >\n        If known, otherwise please leave blank.\n  - type: markdown # Details Section Header\n    attributes:\n      value: |\n        # Details\n  - type: textarea # Minimum Working Example Input\n    attributes:\n      label: Minimum Working Example\n      description: |\n        If you can, providing an MWE to reproduce the issue you're encountering can greatly speed up\n        investigation into the issue by one of our maintainers, or anyone else in the community who's looking\n        to get involved.\n\n        This can be as simple as a script, a link to a repo, etc.\n        If using a script please wrap with triple backticks and language. EG:\n        ` ```javascript `\n  - type: textarea # Additional Information\n    attributes:\n      label: Additional information\n      description: >\n        If you have any additional information for us that you feel will be valuable, please use the field below.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Have a formatting issue or feature request?\n    url: https://github.com/winstonjs/logform/issues/new/choose\n    about: Please search and report @ WinstonJS/Logform\n  - name: Need help using Winston?\n    url: https://stackoverflow.com/questions/tagged/winston\n    about: Please look on StackOverflow first to see if someone has already answered your question.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "content": "name: Would you like to see a feature implemented?\ndescription: Request a new feature for Winston\ntitle: \"[Feature Request]: \"\nlabels: [\"Feature Request\", \"Needs Investigation\"]\nbody:\n  - type: markdown # Form Header\n    attributes:\n      value: |\n        This issue form is for requesting features only!\n  - type: input # Search Terms\n    validations:\n      required: true\n    attributes:\n      label: 🔎 Search Terms\n      description: >-\n        What search terms did you use when trying to find an existing feature request, looking in both open and closed issues?\n        List them here (comma seperated) so people in the future can find this one more easily.\n  - type: textarea # Feature Definition\n    validations:\n      required: true\n    attributes:\n      label: The vision\n      description: >-\n        Please provide a clear and concise description of the feature you would like to see implemented.\n  - type: markdown # Feature Details Section\n    attributes:\n      value: |\n        # Details\n  - type: textarea # Use Case Input\n    attributes:\n      label: Use case\n      description: |\n        If you desire you can provide use cases for the requested feature.\n  - type: textarea # Additional Information\n    attributes:\n      label: Additional information\n      description: >\n        If you have any additional information for us that you feel will be valuable, please use the field below.\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: github-actions\n    directory: /\n    schedule:\n      interval: weekly\n  - package-ecosystem: npm\n    directory: /\n    schedule:\n      interval: weekly\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI Checks\n\non:\n  pull_request:\n    branches:\n      - main\n      - master\n  push:\n    branches:\n      - main\n      - master\n\npermissions:\n  contents: read #  to fetch code (actions/checkout)\n\njobs:\n  Tests:\n    permissions:\n      contents: read #  to fetch code (actions/checkout)\n      checks: write #  to create new checks (coverallsapp/github-action)\n\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node:\n          - 16\n          - 18\n          - 20\n    steps:\n      - uses: actions/checkout@v6\n      - uses: actions/setup-node@v6\n        with:\n          node-version: ${{ matrix.node }}\n\n      - name: Install Dependencies\n        run: npm clean-install\n\n      - name: Lint\n        run: npm run lint\n\n      - name: Unit Tests (with coverage)\n        run: npm run test:unit\n\n      - name: Integration Tests\n        run: npm run test:integration\n\n      - name: Report test coverage to Coveralls.io\n        if: matrix.node == '20'\n        uses: coverallsapp/github-action@master\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: TypeScript Test\n        run: npm run test:typescript\n"
  },
  {
    "path": ".gitignore",
    "content": "test/*.log\ntest/fixtures/*.json\ntest/fixtures/file/*.log*\ntest/fixtures/logs/*.log*\nnode_modules/\nnode_modules/*\nnpm-debug.log\ncoverage/\ncoverage/*\n.nyc_output/\n.nyc_output/*\n*.log\n.idea\n*.sw*\nyarn.lock\n*.tgz\ndist/\n"
  },
  {
    "path": ".npmignore",
    "content": ".nyc_output/\ncoverage/\ndocs\nexamples/\nscratch/\ntest/\n.*\n*.log\n*.md\nappveyor.yml\ntsconfig.json\njest.config.js\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"arrowParens\": \"avoid\",\n  \"bracketSameLine\": false,\n  \"bracketSpacing\": true,\n  \"embeddedLanguageFormatting\": \"auto\",\n  \"insertPragma\": false,\n  \"jsxSingleQuote\": false,\n  \"printWidth\": 80,\n  \"proseWrap\": \"preserve\",\n  \"quoteProps\": \"as-needed\",\n  \"requirePragma\": false,\n  \"semi\": true,\n  \"singleQuote\": true,\n  \"tabWidth\": 2,\n  \"trailingComma\": \"none\",\n  \"useTabs\": false,\n  \"endOfLine\": \"auto\"\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# CHANGELOG\n\n## [v3.9.0](https://github.com/winstonjs/winston/compare/v3.8.2...v3.9.0)\n### Functionality changes\n* Handle undefined errors in getAllInfo in exception-handler in https://github.com/winstonjs/winston/pull/2208; thanks to new contributor @eivindrs\n* fix: properly allow passing non-array transport in https://github.com/winstonjs/winston/pull/2256; thanks to new contributor @Tanuel\n* fix #1732 (Http Transport uses JSON format options as request options) in https://github.com/winstonjs/winston/pull/2272; thanks to new contributor @MoritzLoewenstein (minor version bump per comment on the issue)\n* fix: add guard clause to prevent FD leak in https://github.com/winstonjs/winston/pull/2301; thanks to new contributor @td-tomasz-joniec\n\n### Dependency updates by @dependabot + CI autotesting\n* Bump eslint from 8.23.0 to 8.32.0 by @dependabot in https://github.com/winstonjs/winston/pull/2209, https://github.com/winstonjs/winston/pull/2236, https://github.com/winstonjs/winston/pull/2258, & https://github.com/winstonjs/winston/pull/2271\n* Bump @babel/core from 7.19.0 to 7.20.12 by @dependabot in https://github.com/winstonjs/winston/pull/2206, https://github.com/winstonjs/winston/pull/2234, https://github.com/winstonjs/winston/pull/2259, & https://github.com/winstonjs/winston/pull/2275\n* Bump @types/node from 18.0.0 to 18.11.18 by @dependabot in https://github.com/winstonjs/winston/pull/2215, https://github.com/winstonjs/winston/pull/2235, & https://github.com/winstonjs/winston/pull/2264\n* Bump @babel/preset-env from 7.19.0 to 7.20.2 by @dependabot in https://github.com/winstonjs/winston/pull/2218 & https://github.com/winstonjs/winston/pull/2244\n* Bump safe-stable-stringify from 2.3.1 to 2.4.3 by @dependabot in https://github.com/winstonjs/winston/pull/2217 & https://github.com/winstonjs/winston/pull/2292\n* Bump @babel/cli from 7.18.10 to 7.19.3 by @dependabot in https://github.com/winstonjs/winston/pull/2216\n* Bump json5 from 2.2.1 to 2.2.3 by @dependabot in https://github.com/winstonjs/winston/pull/2260\n\n### Documentation changes\n* Fix readme typo in https://github.com/winstonjs/winston/pull/2230; thanks to new contributor @aretecode\n* create new example for ready to use in https://github.com/winstonjs/winston/pull/2240; thanks to new contributor @myagizmaktav\n* minor fixes to publishing.md\n\n### Build Infrastructure changes\n* GitHub Workflows security hardening in https://github.com/winstonjs/winston/pull/2252; thanks to new contributor @sashashura\n\n## [v3.8.2](https://github.com/winstonjs/winston/compare/v3.8.1...v3.8.2)\n### Patch-level changes\n* Add `.js` to main entry point in package.json in https://github.com/winstonjs/winston/pull/2177; thanks to new contributor @rumanbsl\n* Small grammatical fixes in README.md in https://github.com/winstonjs/winston/pull/2183; thanks to new contributor @mikebarr24\n* Move colors to non-dev dependencies by @wbt in https://github.com/winstonjs/winston/pull/2190\n\n### Dependency updates by @dependabot + CI autotesting\n* Bump @babel/preset-env from 7.18.2 to 7.19.0 in https://github.com/winstonjs/winston/pull/2189\n* Bump @babel/cli from 7.17.10 to 7.18.10 in https://github.com/winstonjs/winston/pull/2173\n* Bump eslint from 8.18.0 to 8.23.0 in https://github.com/winstonjs/winston/pull/2184\n* Bump @babel/core from 7.18.5 to 7.19.0 in https://github.com/winstonjs/winston/pull/2192\n* Bump logform from 2.4.1 to 2.4.2 in https://github.com/winstonjs/winston/pull/2191\n\n## [v3.8.1](https://github.com/winstonjs/winston/compare/v3.8.0...v3.8.1)\n\n### Patch-level changes\n* Update types to match in-code definitions in https://github.com/winstonjs/winston/pull/2157; thanks to new contributor @flappyBug\n\n### Dependency updates by @dependabot + CI autotesting\n* Bump logform from 2.4.0 to 2.4.1 in https://github.com/winstonjs/winston/pull/2156\n* Bump async from 3.2.3 to 3.2.4 in https://github.com/winstonjs/winston/pull/2147\n## [v3.8.0](https://github.com/winstonjs/winston/compare/v3.7.2...v3.8.0) / 2022-06-23\n### Added functionality\n* Add the stringify replacer option to the HTTP transport by @domiins in https://github.com/winstonjs/winston/pull/2155\n\n### Dependency updates by @dependabot + CI autotesting\n* Bump @babel/core from 7.17.8 to 7.18.5\n* Bump eslint from 8.12.0 to 8.18.0\n* Bump @types/node from 17.0.23 to 18.0.0\n* Bump @babel/preset-env from 7.16.11 to 7.18.2\n* Bump @babel/cli from 7.17.6 to 7.17.10\n\n### Updates facilitating repo maintenance & enhancing documentation\n* Explicitly note that the Contributing.md file is out of date\n* Add instructions for publishing updated version by @wbt (docs/publishing.md)\n* Prettier Config File by @jeanpierrecarvalho in https://github.com/winstonjs/winston/pull/2092\n* Readme update to explain origin of errors for handling (#2120)\n* update documentation for #2114 by @zizifn in https://github.com/winstonjs/winston/pull/2138\n* enhance message for logs with no transports #2114 by @zizifn in https://github.com/winstonjs/winston/pull/2139\n* Added a new Community Transport option to the list: Worker Thread based async Console Transport by @arpad1337 in https://github.com/winstonjs/winston/pull/2140\n\nThanks especially to new contributors @zizifn, @arpad1337, @domiins, & @jeanpierrecarvalho!\n\n## v3.7.2 / 2022-04-04\nThis change reverts what should have been the feature-level update in 3.7.0 due to issue #2103 showing this to be breaking, unintentionally.\n\n## v3.7.1 / 2022-04-04\nThis change includes some minor updates to package-lock.json resolving npm audit failures: one in [ansi-regex](https://github.com/advisories/GHSA-93q8-gq69-wqmw) and another in [minimist](https://github.com/advisories/GHSA-xvch-5gv4-984h).\n\n## v3.7.0 / 2022-03-30\n\nFeature-level updates:\n- [#1989] Fix: resolve issues with metadata and the associated overriding behavior (thanks @maverick1872, @wbt, @DABH, @fearphage and issue reporters)\n\nPatch-level updates:\n- [#2075] Fix: add missing types for batching options for HTTP Transport (thanks @KylinDC)\n- Various dependencies updated, quality of life & maintainability changes, etc\n\n## v3.6.0 / 2022-02-12\n\n- [#2057] Fix potential memory leak by not waiting for `process.nextTick` before clearing pending callbacks (thanks @smashah!)\n- [#2071] Update to `logform` 2.4.0, which includes changes such as new options for `JsonOptions` and some typo fixes regarding levels\n- Various other dependencies are updated, tests are reorganized and cleaned up, etc. (thanks @wbt, @Maverick1872, @fearphage!)\n\n## v3.5.1 / 2022-01-31\n\nThis release reverts the changes made in PR #1896 which added stricter typing to the available log levels,\nand inadvertently broke use of custom levels with TypeScript (Issue #2047). Apologies for that!\n\n## v3.5.0 / 2022-01-27\n\nThis release includes the following, in sequence by first merge in group:\n\nFeature updates:\n -\tSupport batch mode in HTTP Transport (Issue #1970, PR #1998, thanks @BBE78!)\n\nPatch-level updates:\n -\tBump dependency versions (thanks @dependabot & @DABH!)\n    -\tBump @types/node from 16.11.12 to 17.0.8 (PR #2009)\n    -\tBump @babel/preset-env from 7.16.7 to 7.16.8 (#2036)\n    -\tBump @types/node from 17.0.8 to 17.0.9 (#2035)\n    -\tBump @babel/cli from 7.16.7 to 7.16.8 (#2034)\n    -\tBump @types/node from 17.0.9 to 17.0.10 (#2042)\n    -\tBump @babel/core from 7.16.7 to 7.16.12 (#2041)\n    -\tBump @babel/preset-env from 7.16.8 to 7.16.11 (#2040)\n -\tFixing documentation syntax errors in transports code examples (#1916; thanks @romanzaycev!)\n -\tFix missing type declarations, especially for `.rejections`\n (#1842, #1929, #2021; thanks @vanflux, @svaj, @glensc, & others!)\n -\tMore narrowly typing the “level” string (#1896, thanks @yonas-g!)\n -\tUsing a safer `stringify`, e.g. to avoid issues from circular structures, in the http transport\n (#2043, thanks @karlwir!)\n\nUpdates to the repo & project which don’t actually affect the running code:\n -\tAdd a channel for reporting security vulnerabilities (#2024, thanks @JamieSlome!)\n -\tAdd coverage tracking in CI & documentation (#2025 and #2028, thanks @fearphage!)\n -\tUpdate issue templates (#2030 and #2031, thanks @Maverick1872!)\n -\tRemove gitter link from README.md (#2027, thanks @DABH!)\n\nThanks also to maintainers @DABH, @fearphage, @Maverick1872, and @wbt for issue/PR shepherding\nand help across multiple parts of the release!\nIf somebody got missed in the list of thanks, please forgive the accidental oversight\nand/or feel free to open a PR on this changelog.\n\n## v3.4.0 / 2022-01-10\n\nYesterday's release was done with a higher sense of urgency than usual\ndue to vandalism in the `colors` package.\nThis release:\n\n - ties up a loose end by including [#1973] to go with [#1824]\n - adds a missing http property in NpmConfigSetColors [#2004] (thanks @SimDaSong)\n - fixes a minor issue in the build/release process [#2014]\n - pins the version of the testing framework to avoid an issue with a test incorrectly failing [#2017]\n\nThe biggest change in this release, motivating the feature-level update, is\n[#2006] Make winston more ESM friendly, thanks to @miguelcobain.\n\nThanks also to @DABH, @wbt, and @fearphage for contributions and reviews!\n\n## v3.3.4 / 2022-01-09\n\nCompared to v3.3.3, this version fixes some issues and includes some updates to project infrastructure,\nsuch as replacing Travis with Github CI and dependabot configuration.\nThere have also been several relatively minor improvements to documentation, and incorporation of some updated dependencies.\nDependency updates include a critical bug fix [#2008] in response to self-vandalism by the author of a dependency.\n\n- [#1964] Added documentation for how to use a new externally maintained [Seq](https://datalust.co/seq) transport.\n- [#1712] Add default metadata when calling log with string level and message.\n- [#1824] Unbind event listeners on close\n- [#1961] Handle undefined rejections\n- [#1878] Correct boolean evaluation of empty-string value for eol option\n- [#1977] Improved consistency of object parameters for better test reliability\n\n## v3.3.3 / 2020-06-23\n\n- [#1820] Revert [#1807] to resolve breaking changes for Typescript users.\n\n## v3.3.2 / 2020-06-22\n\n- [#1814] Use a fork of `diagnostics` published to NPM to avoid git dependency.\n\n## v3.3.1 / 2020-06-21\n\n- [#1803], [#1807] Fix TypeScript bugs.\n- [#1740] Add space between `info.message` and `meta.message`.\n- [#1813] Avoid indirect storage-engine dependency.\n- [#1810] README updates.\n\n## v3.3.0 / 2020-06-21\n\n- [#1779] Fix property name in rejection handler.\n- [#1768] Exclude extraneous files from NPM package.\n- [#1364], [#1714] Don't remove transport from logger when transport error\n  occurs.\n- [#1603] Expose `child` property on default logger.\n- [#1777] Allow HTTP transport to pass options to request.\n- [#1662] Add bearer auth capabilities to HTTP transport.\n- [#1612] Remove no-op in file transport.\n- [#1622], [#1623], [#1625] Typescript fixes.\n- (Minor) [#1647], [#1793] Update CI settings.\n- (Minor) [#1600], [#1605], [#1593], [#1610], [#1654], [#1656], [#1661],\n  [#1651], [#1652], [#1677], [#1683], [#1684], [#1700], [#1697], [#1650],\n  [#1705], [#1723], [#1737], [#1733], [#1743], [#1750], [#1754], [#1780],\n  [#1778] README, Transports.md, other docs changes.\n- [#1672], [#1686], [#1772] Update dependencies.\n\n## v3.2.1 / 2019-01-29\n### UNBOUND PROTOTYPE AD INFINITUM EDITION\n\n- #[1579], (@indexzero)  Fallback to the \"root\" instance **always** created by\n  `createLogger` for level convenience methods (e.g. `.info()`, `.silly()`).\n  (Fixes [#1577]).\n- [#1539], (@indexzero) Assume message is the empty string when level-helper\n  methods are invoked with no arguments (Fixed [#1501]).\n- [#1583], (@kibertoad) Add typings for defaultMeta (Fixes [#1582])\n- [#1586], (@kibertoad) Update dependencies.\n\n## v3.2.0 / 2019-01-26\n### SORRY IT TOO SO LONG EDITION\n\n> **NOTE:** this was our first release using Github Projects. See the\n> [3.2.0 Release Project](https://github.com/orgs/winstonjs/projects/3).\n\n### New Features!\n\n- [#1471], (@kibertoad) Implement child loggers.\n- [#1462], (@drazisil) Add handleRejection support.\n  - [#1555], (@DABH) Add fixes from [#1355] to unhandled rejection handler.\n- [#1418], (@mfrisbey) Precompile ES6 syntax before publishing to npm.\n  - [#1533], (@kibertoad) Update to Babel 7.\n- [#1562], (@indexzero) [fix] Better handling of `new Error(string)`\n  throughout the pipeline(s). (Fixes [#1338], [#1486]).\n\n### Bug Fixes\n\n- [#1355], (@DABH) Fix issues with ExceptionHandler (Fixes [#1289]).\n- [#1463], (@SerayaEryn) Bubble transport `warn` events up to logger in\n  addition to `error`s.\n- [#1480], [#1503], (@SerayaEryn) File tailrolling fix.\n- [#1483], (@soldair) Assign log levels to un-bound functions.\n- [#1513], (@TilaTheHun0) Set maxListeners for Console transport.\n- [#1521], (@jamesbechet) Fix Transform from `readable-stream` using CRA.\n- [#1434], (@Kouzukii) Fixes logger.query function (regression from `3.0.0`)\n- [#1526], (@pixtron) Log file without .gz for tailable (Fixes [#1525]).\n- [#1559], (@eubnara) Fix typo related to `exitOnError`.\n- [#1556], (@adoyle-h) Support to create log directory if it doesn't exist\n  for FileTransport.\n\n#### New `splat` behavior\n\n- [#1552], (@indexzero) Consistent handling of meta with (and without)\n  interpolation in `winston` and `logform`.\n- [#1499], (@DABH) Provide all of `SPLAT` to formats (Fixes [#1485]).\n- [#1485], (@mpabst) Fixing off-by-one when using both meta and splat.\n\nPreviously `splat` would have added a `meta` property for any additional\n`info[SPLAT]` beyond the expected number of tokens.\n\n**As of `logform@2.0.0`,** `format.splat` assumes additional splat paramters\n(aka \"metas\") are objects and merges enumerable properties into the `info`.\ne.g. **BE ADVISED** previous \"metas\" that _were not objects_ will very likely\nlead to odd behavior. e.g.\n\n``` js\nconst { createLogger, format, transports } = require('winston');\nconst { splat } = format;\nconst { MESSAGE, LEVEL, SPLAT } = require('triple-beam');\n\nconst logger = createLogger({\n  format: format.combine(\n    format.splat(),\n    format.json()\n  ),\n  transports: [new transports.Console()]\n});\n\n// Expects two tokens, but four splat parameters provided.\nlogger.info(\n  'Let us %s for %j',   // message\n  'objects',           // used for %s\n  { label: 'sure' },   // used for %j\n  'lol', ['ok', 'why'] // Multiple additional meta values\n);\n\n// winston < 3.2.0 && logform@1.x behavior:\n// Added \"meta\" property.\n//\n// { level: 'info',\n//   message: 'Let us objects for {\"label\":\"sure\"}',\n//   meta: ['lol', ['ok', 'why']],\n//   [Symbol(level)]: 'info',\n//   [Symbol(message)]: 'Let us %s for %j',\n//   [Symbol(splat)]: [ 'objects', { label: 'sure' } ] }\n\n// winston >= 3.2.0 && logform@2.x behavior: Enumerable properties\n// assigned into `info`. Since **strings and Arrays only have NUMERIC\n// enumerable properties we get this behavior!**\n//\n// { '0': 'ok',\n//   '1': 'why',\n//   '2': 'l',\n//   level: 'info',\n//   message: 'Let us objects for {\"label\":\"sure\"}',\n//   [Symbol(level)]: 'info',\n//   [Symbol(message)]: 'Let us %s for %j',\n//   [Symbol(splat)]: [ 'objects', { label: 'sure' } ] }\n```\n\n## Maintenance & Documentation\n\n- Documentation Updates\n  - [#1410], (@hakanostrom) Add docs reference to transport for Cloudant.\n  - [#1467], (@SeryaEryn) Add fast-file-rotate transport to transport.md.\n  - [#1488], (@adamcohen) Fix multi logger documentation.\n  - [#1531], (@mapleeit) Add links to transports.\n  - [#1548], (@ejmartin504) Fix `README.md` for awaiting logs.\n  - [#1554], (@indexzero) Document the solution to [#1486] as by design.\n  - Other small improvements: [#1509].\n- Improved TypeScript support\n  - [#1470], (@jd-carroll) Export all transport options (Fixes [#1469]).\n  - [#1474], (@jd-carroll) Correct import to avoid conflict (Fixed [#1472]).\n  - [#1546], (@alewiahmed) Add consoleWarnLevels field to the\n    `ConsoleTransportOptions` interface type definition.\n  - [#1557], (@negezor) Add missing `child()` method.\n- Dependency management\n  - [#1560], (@kibertoad) Update dependencies.\n  - [#1512], (@SerayaEryn) Add node@11 and disallow failures on node@10.\n  - [#1516], (@SerayaEryn) Update `readable-stream` to `v3.0.6`.\n  - [#1534], (@kibertoad) Update `@types/node`, `nyc`, and `through2`.\n\n## v3.1.0 / 2018-08-22\n### RELEASES ON A PLANE EDITION\n\n- Minor TypeScript fixes [#1362], [#1395], [#1440]\n- Fix minor typos [#1359], [#1363], [#1372], [#1378], [#1390]\n- [#1373], (@revik): Add `consoleWarnLevels` property to console transport options for `console.warn` browser support.\n- [#1394], (@bzoz): Fix tests on Windows.\n- [#1447], (@dboshardy): Support transport name option to override default names for built-in transports.\n- [#1420], (@ledbit): Fix file rotation with `tailing: true` (Fixes [#1450], [#1194]).\n- [#1352], (@lutovich): Add `isLevelEnabled(string)` & `isXXXEnabled()` to `Logger` class.\n- Dependency management\n  - Regenerate `package-lock.json`.\n  - Upgrade to `colors@^1.3.2` (Fixes [#1439]).\n  - Upgrade to `logform@^1.9.1`.\n  - Upgrade to `diagnostics@^1.1.1`.\n  - Upgrade to `@types/node@^10.9.3`.\n  - Upgrade to `assume@^2.1.0`.\n  - Upgrade to `hock@^1.3.3`.\n  - Upgrade to `mocha@^5.2.0`.\n  - Upgrade to `nyc@^13.0.1`.\n  - Upgrade to `split2@^3.0.0`.\n\n## v3.0.0 / 2018-06-12\n### GET IN THE CHOPPA EDITION\n\n- [#1332], (@DABH): logger.debug is sent to stderr (Fixed [#1024])\n- [#1328], (@ChrisAlderson): Logger level doesn't update transports level (Fixes [#1191]).\n- [#1356], (@indexzero) Move splat functionality into logform. (Fixes [#1298]).\n- [#1340], (@indexzero): Check log.length when evaluating \"legacyness\" of transports (Fixes [#1280]).\n- [#1346], (@indexzero): Implement `_final` from Node.js streams. (Related to winston-transport#24, Fixes [#1250]).\n- [#1347], (@indexzero): Wrap calls to `format.transform` with try / catch (Fixes [#1261]).\n- [#1357], (@indexzero): Remove paddings as we have no use for it in the current API.\n- [TODO]: REMAINS OPEN, NO PR (Fixes [#1289])\n- Documentation\n  - [#1301], (@westonpace) Cleaned up some of the documentation on `colorize`\n    to address concerns in [#1095].\n  - First pass at a heavy refactor of `docs/transports.md`.\n- Dependency management\n  - Regenerate `package-lock.json`.\n  - Upgrade to `logform@^1.9.0`.\n\n## v3.0.0-rc6 / 2018-05-30\n### T-MINUS 6-DAY TO WINSTON@3 EDITION\n\n- **Document that we are pushing for a June 5th, 2018 release of `winston@3.0.0`**\n- [#1287], (@DABH) Added types for Typescript.\n  - [#1335] Typescript: silent is boolean.\n  - [#1323] Add level method to default logger.\n- [#1286], (@ChrisAlderson) Migrate codebase to ES6\n  - [#1324], (@ChrisAlderson) Fix regression introduced by ES6 migration for\n    exception handling.\n  - [#1333], (@ChrisAlderson) Fix removing all loggers from a container.\n- [#1291], [#1294], [#1318], (@indexzero, @ChrisAlderson, @mempf) Improvements\n  to `File` transport core functionality. Fixes [#1194].\n- [#1311], (@ChrisAlderson) Add `eol` option to `Stream` transport.\n- [#1297], (@ChrisAlderson) Move `winston.config` to `triple-beam`. Expose\n  for backwards compatibility.\n- [#1320], (@ChrisAlderson) Enhance tests to run on Windows.\n- Internal project maintenance\n  - Bump to `winston-transport@4.0.0` which may cause incompatibilities if\n    your custom transport does not explicitly require `winston-transport`\n    itself.\n  - [#1292], (@ChrisAlderson) Add node v10 to TravisCI build matrix.\n  - [#1296], (@indexzero) Improve `UPGRADE-3.0.md`. Add Github Issue Template.\n  - Remove \"npm run report\" in favor of reports being automatically generate.\n  - Update `logform`, `triple-beam`, and `winston-transport` to latest.\n\n> Special thanks to our newest `winston` core team member – @ChrisAlderson for\n> helping make `winston@3.0.0` a reality next week!\n\n## v3.0.0-rc5 / 2018-04-20\n### UNOFFICIAL NATIONAL HOLIDAY EDITION\n\n- [#1281] Use `Buffer.alloc` and `Buffer.from` instead of `new Buffer`.\n- Better browser support\n  - [#1142] Move common tailFile to a separate file\n  - [#1279] Use feature detection to be safer for browser usage.\n- MOAR Docs!\n  - **Document that we are pushing for a May 29th, 2018 release of `winston@3.0.0`**\n  - **Add David Hyde as official contributor.**\n  - [#1278] Final Draft of Upgrade Guide in `UPGRADE-3.0.md`\n  - Merge Roadmap from `3.0.0.md` into `CONTRIBUTING.md` and other\n    improvements to `CONTRIBUTING.md`\n- Improve & expand examples\n  - [#1175] Add more copy about printf formats based on issue feedback.\n  - [#1134] Add sampleto document timestamps more clearly as an example.\n  - [#1273] Add example using multiple formats.\n  - [#1250] Add an example illustrating the \"finish\" event for AWS Lambda scenarios.\n  - Use simple format to better show that `humanReadableUnhandledException` is now the default message format.\n  - Add example to illustrate that example code from winston-transport\n    `README.md` is correct.\n- Update `devDependencies`\n  - Bump `assume` to `^2.0.1`.\n  - Bump `winston-compat` to `^0.1.1`.\n\n## v3.0.0-rc4 / 2018-04-06\n### IF A TREE FALLS IN THE FORREST DOES IT MAKE A LOG EDITION\n\n- (@indexzero, @dabh) Add support for `{ silent }` option to\n``` js\nrequire('winston').Logger;\nrequire('winston-transport').TransportStream;\n```\n- Better browser support\n  - [#1145], (@Jasu) Replace `isstream` with `is-stream` to make stream detection work in browser.\n  - [#1146], (@Jasu) Rename query to different than function name, to support Babel 6.26.\n- Better Typescript support in all supporting libraries\n  - `logform@1.4.1`\n- Update documentation\n  - (@indexzero) Correct link to upgrade guide. Fixes #1255.\n  - [#1258], (@morenoh149) Document how to colorize levels. Fixes #1135.\n  - [#1246], (@KlemenPlazar) Update colors argument when adding custom colors\n  - Update `CONTRIBUTING.md`\n  - [#1239], (@dabh) Add changelog entries for `v3.0.0-rc3`\n  - Add example showing that `{ level }` can be deleted from info objects because `Symbol.for('level')` is what `winston` uses internally. Fixes #1184.\n\n## v3.0.0-rc3 / 2018-03-16\n### I GOT NOTHING EDITION\n\n- [#1195], (@Nilegfx) Fix type error when creating `new stream.Stream()`\n- [#1109], (@vsetka) Fix file transprot bug where `self.filename` was not being updated on `ENOENT`\n- [#1153], (@wizardnet972) Make prototype methods return like the original method\n- [#1234], (@guiguan, @indexzero) Add tests for properly handling logging of `undefined`, `null` and `Error` values\n- [#1235], (@indexzero) Add example demonstrating how `meta` objects BECOME the `info` object\n- Minor fixes to docs & examples: [#1232], [#1185]\n\n## v3.0.0-rc2 / 2018-03-09\n### MAINTENANCE RESUMES EDITION\n\n- [#1209], (@dabh) Use new version of colors, solving a number of issues.\n- [#1197], (@indexzero) Roadmap & guidelines for contributors.\n- [#1100] Require the package.json by its full name.\n- [#1149] Updates `async` to latest (`2.6.0`)\n- [#1228], (@mcollina) Always pass a function to `fs.close`.\n- Minor fixes to docs & examples: [#1177], [#1182], [#1208], [#1198], [#1165], [#1110], [#1117], [#1097], [#1155], [#1084], [#1141], [#1210], [#1223].\n\n## v3.0.0-rc1 / 2017-10-19\n### OMG THEY FORGOT TO NAME IT EDITION\n\n - Fix file transport improper binding of `_onDrain` and `_onError` [#1104](https://github.com/winstonjs/winston/pull/1104)\n\n## v3.0.0-rc0 / 2017-10-02\n### IT'S-DONE.GIF EDITION\n\n**See [UPGRADE-3.0.md](UPGRADE-3.0.md) for a complete & living upgrade guide.**\n\n**See [3.0.0.md](3.0.0.md) for a list of remaining RC tasks.**\n\n- **Rewrite of core logging internals:** `Logger` & `Transport` are now implemented using Node.js `objectMode` streams.\n- **Your transports _should_ not break:** Special attention has been given to ensure backwards compatibility with existing transports. You will likely see this:\n```\nYourTransport is a legacy winston transport. Consider upgrading to winston@3:\n- Upgrade docs: https://github.com/winstonjs/winston/tree/master/UPGRADE.md\n```\n- **`filters`, `rewriters`, and `common.log` are now _formats_:** `winston.format` offers a simple mechanism for user-land formatting & style features. The organic & frankly messy growth of `common.log` is of the past; these feature requests can be implemented entirely outside of `winston` itself.\n``` js\nconst { createLogger, format, transports } = require('winston');\nconst { combine, timestamp, label, printf } = format;\n\nconst myFormat = printf(info => {\n  return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`;\n});\n\nconst logger = createLogger({\n  combine(\n    label({ label: 'right meow!' }),\n    timestamp(),\n    myFormat\n  ),\n  transports: [new transports.Console()]\n});\n```\n- **Increased modularity:** several subsystems are now stand-alone packages:\n  - [logform] exposed as `winston.format`\n  - [winston-transport] exposed as `winston.Transport`\n  - [abstract-winston-transport] used for reusable unit test suites for transport authors.\n- **`2.x` branch will get little to no maintenance:** no feature requests will be accepted – only a limited number of open PRs will be merged. Hoping the [significant performance benefits][perf-bench] incentivizes folks to upgrade quickly. Don't agree? Say something!\n- **No guaranteed support for `node@4` or below:** all code will be migrated to ES6 over time. This release was started when ES5 was still a hard requirement due to the current LTS needs.\n\n## v2.4.0 / 2017-10-01\n### ZOMFG WINSTON@3.0.0-RC0 EDITION\n\n- [#1036] Container.add() 'filters' and 'rewriters' option passing to logger.\n- [#1066] Fixed working of \"humanReadableUnhandledException\" parameter when additional data is added in meta.\n- [#1040] Added filtering by log level\n- [#1042] Fix regressions brought by `2.3.1`.\n  - Fix regression on array printing.\n  - Fix regression on falsy value.\n- [#977] Always decycle objects before cloning.\n  - Fixes [#862]\n  - Fixes [#474]\n  - Fixes [#914]\n- [57af38a] Missing context in `.lazyDrain` of `File` transport.\n- [178935f] Suppress excessive Node warning from `fs.unlink`.\n- [fcf04e1] Add `label` option to `File` transport docs.\n- [7e736b4], [24300e2] Added more info about undocumented `winston.startTimer()` method.\n- [#1076], [#1082], [#1029], [#989], [e1e7188] Minor grammatical & style updates to `README.md`.\n\n## v2.3.1 / 2017-01-20\n### WELCOME TO THE APOCALYPSE EDITION\n\n- [#868](https://github.com/winstonjs/winston/pull/868), Fix 'Maximum call stack size exceeded' error with custom formatter.\n\n## v2.3.0 / 2016-11-02\n### ZOMG WHY WOULD YOU ASK EDITION\n\n- Full `CHANGELOG.md` entry forthcoming. See [the `git` diff for `2.3.0`](https://github.com/winstonjs/winston/compare/2.2.0...2.3.0) for now.\n\n## v2.2.0 / 2016-02-25\n### LEAVING CALIFORNIA EDITION\n\n- Full `CHANGELOG.md` entry forthcoming. See [the `git` diff for `2.2.0`](https://github.com/winstonjs/winston/compare/2.1.1...2.2.0) for now.\n\n## v2.1.1 / 2015-11-18\n### COLOR ME IMPRESSED EDITION\n\n- [#751](https://github.com/winstonjs/winston/pull/751), Fix colors not appearing in non-tty environments. Fixes [#609](https://github.com/winstonjs/winston/issues/609), [#616](https://github.com/winstonjs/winston/issues/616), [#669](https://github.com/winstonjs/winston/issues/669), [#648](https://github.com/winstonjs/winston/issues/648) (`fiznool`).\n- [#752](https://github.com/winstonjs/winston/pull/752)     Correct syslog RFC number. 5424 instead of 524. (`jbenoit2011`)\n\n## v2.1.0 / 2015-11-03\n### TEST ALL THE ECOSYSTEM EDITION\n\n- [#742](https://github.com/winstonjs/winston/pull/742), [32d52b7](https://github.com/winstonjs/winston/commit/32d52b7) Distribute common test files used by transports in the `winston` ecosystem.\n\n## v2.0.1 / 2015-11-02\n### BUGS ALWAYS HAPPEN OK EDITION\n\n- [#739](https://github.com/winstonjs/winston/issues/739), [1f16861](https://github.com/winstonjs/winston/commit/1f16861) Ensure that `logger.log(\"info\", undefined)` does not throw.\n\n## v2.0.0 / 2015-10-29\n### OMG IT'S MY SISTER'S BIRTHDAY EDITION\n\n#### Breaking changes\n\n**Most important**\n- **[0f82204](https://github.com/winstonjs/winston/commit/0f82204) Move `winston.transports.DailyRotateFile` [into a separate module](https://github.com/winstonjs/winston-daily-rotate-file)**: `require('winston-daily-rotate-file');`\n- **[fb9eec0](https://github.com/winstonjs/winston/commit/fb9eec0) Reverse log levels in `npm` and `cli` configs to conform to [RFC524](https://tools.ietf.org/html/rfc5424). Fixes [#424](https://github.com/winstonjs/winston/pull/424) [#406](https://github.com/winstonjs/winston/pull/406) [#290](https://github.com/winstonjs/winston/pull/290)**\n- **[8cd8368](https://github.com/winstonjs/winston/commit/8cd8368) Change the method signature to a `filter` function to be consistent with `rewriter` and log functions:**\n``` js\nfunction filter (level, msg, meta, inst) {\n  // Filter logic goes here...\n}\n```\n\n**Other breaking changes**\n- [e0c9dde](https://github.com/winstonjs/winston/commit/e0c9dde) Remove `winston.transports.Webhook`. Use `winston.transports.Http` instead.\n- [f71e638](https://github.com/winstonjs/winston/commit/f71e638) Remove `Logger.prototype.addRewriter` and `Logger.prototype.addFilter` since they just push to an Array of functions. Use `logger.filters.push` or `logger.rewriters.push` explicitly instead.\n- [a470ab5](https://github.com/winstonjs/winston/commit/a470ab5) No longer respect the `handleExceptions` option to `new winston.Logger`. Instead just pass in the `exceptionHandlers` option itself.\n- [8cb7048](https://github.com/winstonjs/winston/commit/8cb7048) Removed `Logger.prototype.extend` functionality\n\n#### New features\n- [3aa990c](https://github.com/winstonjs/winston/commit/3aa990c) Added `Logger.prototype.configure` which now contains all logic previously in the `winston.Logger` constructor function. (`indexzero`)\n- [#726](https://github.com/winstonjs/winston/pull/726) Update .npmignore (`coreybutler`)\n- [#700](https://github.com/winstonjs/winston/pull/700) Add an `eol` option to the `Console` transport. (`aquavitae`)\n- [#731](https://github.com/winstonjs/winston/pull/731) Update `lib/transports.js` for better static analysis. (`indexzero`)\n\n#### Fixes, refactoring, and optimizations. OH MY!\n- [#632](https://github.com/winstonjs/winston/pull/632) Allow `File` transport to be an `objectMode` writable stream. (`stambata`)\n- [#527](https://github.com/winstonjs/winston/issues/527), [163f4f9](https://github.com/winstonjs/winston/commit/163f4f9), [3747ccf](https://github.com/winstonjs/winston/commit/3747ccf) Performance optimizations and string interpolation edge cases (`indexzero`)\n- [f0edafd](https://github.com/winstonjs/winston/commit/f0edafd) Code cleanup for reability, ad-hoc styleguide enforcement (`indexzero`)\n\n## v1.1.1 - v1.1.2 / 2015-10\n### MINOR FIXES EDITION\n\n#### Notable changes\n  * [727](https://github.com/winstonjs/winston/pull/727) Fix \"raw\" mode (`jcrugzz`)\n  * [703](https://github.com/winstonjs/winston/pull/703) Do not modify Error or Date objects when logging. Fixes #610 (`harriha`).\n\n## v1.1.0 / 2015-10-09\n### GREETINGS FROM CARTAGENA EDITION\n\n#### Notable Changes\n  * [#721](https://github.com/winstonjs/winston/pull/721) Fixed octal literal to work with node 4 strict mode (`wesleyeff`)\n  * [#630](https://github.com/winstonjs/winston/pull/630) Add stderrLevels option to Console Transport and update docs (`paulhroth`)\n  * [#626](https://github.com/winstonjs/winston/pull/626) Add the logger (this) in the fourth argument in the rewriters and filters functions (`christophehurpeau `)\n  * [#623](https://github.com/winstonjs/winston/pull/623) Fix Console Transport's align option tests (`paulhroth`, `kikobeats`)\n  * [#692](https://github.com/winstonjs/winston/pull/692) Adding winston-aws-cloudwatch to transport docs (`timdp`)\n\n## v1.0.2 2015-09-25\n### LET'S TALK ON GITTER EDITION\n\n#### Notable Changes\n  * [de80160](https://github.com/winstonjs/winston/commit/de80160) Add Gitter badge (`The Gitter Badger`)\n  * [44564de](https://github.com/winstonjs/winston/commit/44564de) [fix] Correct listeners in `logException`. Fixes [#218](https://github.com/winstonjs/winston/issues/218) [#213](https://github.com/winstonjs/winston/issues/213) [#327](https://github.com/winstonjs/winston/issues/327). (`indexzero`)\n  * [45b1eeb](https://github.com/winstonjs/winston/commit/45b1eeb) [fix] Get `tailFile` function working on latest/all node versions (`Christopher Jeffrey`)\n  * [c6d45f9](https://github.com/winstonjs/winston/commit/c6d45f9) Fixed event subscription on close (`Roman Stetsyshin`)\n\n#### Other changes\n  * TravisCI updates & best practices [87b97cc](https://github.com/winstonjs/winston/commit/87b97cc) [91a5bc4](https://github.com/winstonjs/winston/commit/91a5bc4), [cf24e6a](https://github.com/winstonjs/winston/commit/cf24e6a) (`indexzero`)\n  * [d5397e7](https://github.com/winstonjs/winston/commit/d5397e7) Bump async version (`Roderick Hsiao`)\n  * Documentation updates & fixes [86d7527](https://github.com/winstonjs/winston/commit/86d7527), [38254c1](https://github.com/winstonjs/winston/commit/38254c1), [04e2928](https://github.com/winstonjs/winston/commit/04e2928), [61c8a89](https://github.com/winstonjs/winston/commit/61c8a89), [c42a783](https://github.com/winstonjs/winston/commit/c42a783), [0688a22](https://github.com/winstonjs/winston/commit/0688a22), [eabc113](https://github.com/winstonjs/winston/commit/eabc113) [c9506b7](https://github.com/winstonjs/winston/commit/c9506b7), [17534d2](https://github.com/winstonjs/winston/commit/17534d2), [b575e7b](https://github.com/winstonjs/winston/commit/b575e7b) (`Stefan Thies`, `charukiewicz`, `unLucio`, `Adam Cohen`, `Denis Gorbachev`, `Frederik Ring`, `Luigi Pinca`, `jeffreypriebe`)\n  * Documentation refactor & cleanup [a19607e](https://github.com/winstonjs/winston/commit/a19607e), [d1932b4](https://github.com/winstonjs/winston/commit/d1932b4), [7a13132](https://github.com/winstonjs/winston/commit/7a13132) (`indexzero`)\n\n\n## v1.0.1 / 2015-06-26\n### YAY DOCS EDITION\n\n  * [#639](https://github.com/winstonjs/winston/pull/639) Fix for [#213](https://github.com/winstonjs/winston/issues/213): More than 10 containers triggers EventEmitter memory leak warning (`marcus`)\n  * Documentation and `package.json` updates [cec892c](https://github.com/winstonjs/winston/commit/cec892c), [2f13b4f](https://github.com/winstonjs/winston/commit/2f13b4f), [b246efd](https://github.com/winstonjs/winston/commit/b246efd), [22a5f5a](https://github.com/winstonjs/winston/commit/22a5f5a), [5868b78](https://github.com/winstonjs/winston/commit/5868b78), [99b6b44](https://github.com/winstonjs/winston/commit/99b6b44), [447a813](https://github.com/winstonjs/winston/commit/447a813), [7f75b48](https://github.com/winstonjs/winston/commit/7f75b48) (`peteward44`, `Gilad Peleg`, `Anton Ian Sipos`, `nimrod-becker`, `LarsTi`, `indexzero`)\n\n## v1.0.0 / 2015-04-07\n### OMG 1.0.0 FINALLY EDITION\n\n#### Breaking Changes\n  * [#587](https://github.com/winstonjs/winston/pull/587) Do not extend `String` prototypes as a side effect of using `colors`. (`kenperkins`)\n  * [#581](https://github.com/winstonjs/winston/pull/581) File transports now emit `error` on error of the underlying streams after `maxRetries` attempts. (`ambbell`).\n  * [#583](https://github.com/winstonjs/winston/pull/583), [92729a](https://github.com/winstonjs/winston/commit/92729a68d71d07715501c35d94d2ac06ac03ca08) Use `os.EOL` for all file writing by default. (`Mik13`, `indexzero`)\n  * [#532](https://github.com/winstonjs/winston/pull/532) Delete logger instance from `Container` when `close` event is emitted. (`snater`)\n  * [#380](https://github.com/winstonjs/winston/pull/380) Rename `duration` to `durationMs`, which is now a number a not a string ending in `ms`. (`neoziro`)\n  * [#253](https://github.com/winstonjs/winston/pull/253) Do not set a default level. When `level` is falsey on any `Transport` instance, any `Logger` instance uses the configured level (instead of the Transport level) (`jstamerj`).\n\n#### Other changes\n\n  * [b83de62](https://github.com/winstonjs/winston/commit/b83de62) Fix rendering of stack traces.\n  * [c899cc](https://github.com/winstonjs/winston/commit/c899cc1f0719e49b26ec933e0fa263578168ea3b) Update documentation (Fixes [#549](https://github.com/winstonjs/winston/issues/549))\n  * [#551](https://github.com/winstonjs/winston/pull/551) Filter metadata along with messages\n  * [#578](https://github.com/winstonjs/winston/pull/578) Fixes minor issue with `maxFiles` in `File` transport (Fixes [#556](https://github.com/winstonjs/winston/issues/556)).\n  * [#560](https://github.com/winstonjs/winston/pull/560) Added `showLevel` support to `File` transport.\n  * [#558](https://github.com/winstonjs/winston/pull/558) Added `showLevel` support to `Console` transport.\n\n## v0.9.0 / 2015-02-03\n\n  * [#496](https://github.com/flatiron/winston/pull/496) Updated default option handling for CLI (`oojacoboo`).\n  * [f37634b](https://github.com/flatiron/winston/commit/f37634b) [dist] Only support `node >= 0.8.0`. (`indexzero`)\n  * [91a1e90](https://github.com/flatiron/winston/commit/91a1e90), [50163a0](https://github.com/flatiron/winston/commit/50163a0) Fix #84 [Enable a better unhandled exception experience](https://github.com/flatiron/winston/issues/84) (`samz`)\n  * [8b5fbcd](https://github.com/flatiron/winston/commit/8b5fbcd) #448 Added tailable option to file transport which rolls files backwards instead of creating incrementing appends. Implements #268 (`neouser99`)\n  * [a34f7d2](https://github.com/flatiron/winston/commit/a34f7d2) Custom log formatter functionality were added. (`Melnyk Andii`)\n  * [4c08191](https://github.com/flatiron/winston/commit/4c08191) Added showLevel flag to common.js, file*, memory and console transports. (`Tony Germaneri`)\n  * [64ed8e0](https://github.com/flatiron/winston/commit/64ed8e0) Adding custom pretty print function test. (`Alberto Pose`)\n  * [3872dfb](https://github.com/flatiron/winston/commit/3872dfb) Adding prettyPrint parameter as function example. (`Alberto Pose`)\n  * [2b96eee](https://github.com/flatiron/winston/commit/2b96eee) implemented filters #526 (`Chris Oloff`)\n  * [72273b1](https://github.com/flatiron/winston/commit/72273b1) Added the options to colorize only the level, only the message or all. Default behavior is kept. Using true will only colorize the level and false will not colorize anything. (`Michiel De Mey`)\n  * [178e8a6](https://github.com/flatiron/winston/commit/178e8a6) Prevent message from meta input being overwritten (`Leonard Martin`)\n  * [270be86](https://github.com/flatiron/winston/commit/270be86) [api] Allow for transports to be removed by their string name [test fix] Add test coverage for multiple transports of the same type added in #187. [doc] Document using multiple transports of the same type (`indexzero`)\n  * [0a848fa](https://github.com/flatiron/winston/commit/0a848fa) Add depth options for meta pretty print (`Loïc Mahieu`)\n  * [106b670](https://github.com/flatiron/winston/commit/106b670) Allow debug messages to be sent to stdout (`John Frizelle`)\n  * [ad2d5e1](https://github.com/flatiron/winston/commit/ad2d5e1) [fix] Handle Error instances in a sane way since their properties are non-enumerable __by default.__ Fixes #280. (`indexzero`)\n  * [5109dd0](https://github.com/flatiron/winston/commit/5109dd0) [fix] Have a default `until` before a default `from`. Fixes #478. (`indexzero`)\n  * [d761960](https://github.com/flatiron/winston/commit/d761960) Fix logging regular expression objects (`Chasen Le Hara`)\n  * [2632eb8](https://github.com/flatiron/winston/commit/2632eb8) Add option for EOL chars on FileTransport (`José F. Romaniello`)\n  * [bdecce7](https://github.com/flatiron/winston/commit/bdecce7) Remove duplicate logstash option (`José F. Romaniello`)\n  * [7a01f9a](https://github.com/flatiron/winston/commit/7a01f9a) Update declaration block according to project's style guide (`Ricardo Torres`)\n  * [ae27a19](https://github.com/flatiron/winston/commit/ae27a19) Fixes #306: Can't set customlevels to my loggers (RangeError: Maximum call stack size exceeded) (`Alberto Pose`)\n  * [1ba4f51](https://github.com/flatiron/winston/commit/1ba4f51) [fix] Call `res.resume()` in HttpTransport to get around known issues in streams2. (`indexzero`)\n  * [39e0258](https://github.com/flatiron/winston/commit/39e0258) Updated default option handling for CLI (`Jacob Thomason`)\n  * [8252801](https://github.com/flatiron/winston/commit/8252801) Added logstash support to console transport (`Ramon Snir`)\n  * [18aa301](https://github.com/flatiron/winston/commit/18aa301) Module isStream should be isstream (`Michael Neil`)\n  * [2f5f296](https://github.com/flatiron/winston/commit/2f5f296) options.prettyPrint can now be a function (`Matt Zukowski`)\n  * [a87a876](https://github.com/flatiron/winston/commit/a87a876) Adding rotationFormat prop to file.js (`orcaman`)\n  * [ff187f4](https://github.com/flatiron/winston/commit/ff187f4) Allow custom exception level (`jupiter`)\n\n## 0.8.3 / 2014-11-04\n\n* [fix lowercase issue (`jcrugzz`)](https://github.com/flatiron/winston/commit/b3ffaa10b5fe9d2a510af5348cf4fb3870534123)\n\n## 0.8.2 / 2014-11-04\n\n* [Full fix for #296 with proper streams2 detection with `isstream` for file transport (`jcrugzz`)](https://github.com/flatiron/winston/commit/5c4bd4191468570e46805ed399cad63cfb1856cc)\n* [Add isstream module (`jcrugzz`)](https://github.com/flatiron/winston/commit/498b216d0199aebaef72ee4d8659a00fb737b9ae)\n* [Partially fix #296 with streams2 detection for file transport (`indexzero`)](https://github.com/flatiron/winston/commit/b0227b6c27cf651ffa8b8192ef79ab24296362e3)\n* [add stress test for issue #288 (`indexzero`)](https://github.com/flatiron/winston/commit/e08e504b5b3a00f0acaade75c5ba69e6439c84a6)\n* [lessen timeouts to check test sanity (`indexzero`)](https://github.com/flatiron/winston/commit/e925f5bc398a88464f3e796545ff88912aff7568)\n* [update winston-graylog2 documentation (`unlucio`)](https://github.com/flatiron/winston/commit/49fa86c31baf12c8ac3adced3bdba6deeea2e363)\n* [fix test formatting (`indexzero`)](https://github.com/flatiron/winston/commit/8e2225799520a4598044cdf93006d216812a27f9)\n* [fix so options are not redefined (`indexzero`)](https://github.com/flatiron/winston/commit/d1d146e8a5bb73dcb01579ad433f6d4f70b668ea)\n* [fix self/this issue that broke `http` transport (`indexzero`)](https://github.com/flatiron/winston/commit/d10cbc07755c853b60729ab0cd14aa665da2a63b)\n\n\n## 0.8.1 / 2014-10-06\n\n* [Add label option for DailyRotateFile transport (`francoisTemasys`)](https://github.com/flatiron/winston/pull/459)\n* [fix Logger#transports length check upon Logger#log (`adriano-di-giovanni`, `indexzero`)](https://github.com/flatiron/winston/pull/404)\n* [err can be a string. (`gdw2`, `indexzero`)](https://github.com/flatiron/winston/pull/396)\n* [Added color for pre-defined cli set. (`danilo1105`, `indexzero`)](https://github.com/flatiron/winston/pull/365)\n* [Fix dates on transport test (`revington`)](https://github.com/flatiron/winston/pull/346)\n* [Included the label from options to the output in JSON mode. (`arxony`)](https://github.com/flatiron/winston/pull/326)\n* [Allow using logstash option with the File transport (`gmajoulet`)](https://github.com/flatiron/winston/pull/299)\n* [Be more defensive when working with `query` methods from Transports. Fixes #356. (indexzero)](https://github.com/flatiron/winston/commit/b80638974057f74b521dbe6f43fef2105110afa2)\n* [Catch exceptions for file transport unlinkSync (`calvinfo`)](https://github.com/flatiron/winston/pull/266)\n* [Adding the 'addRewriter' to winston (`machadogj`)](https://github.com/flatiron/winston/pull/258)\n* [Updates to transport documentation (`pose`)](https://github.com/flatiron/winston/pull/262)\n* [fix typo in \"Extending another object with Logging\" section.](https://github.com/flatiron/winston/pull/281)\n* [Updated README.md - Replaced properties with those listed in winston-mongodb module](https://github.com/flatiron/winston/pull/264)\n\n## 0.8.0 / 2014-09-15\n  * [Fixes for HTTP Transport](https://github.com/flatiron/winston/commit/a876a012641f8eba1a976eada15b6687d4a03f82)\n  * Removing [jsonquest](https://github.com/flatiron/winston/commit/4f088382aeda28012b7a0498829ceb243ed74ac1) and [request](https://github.com/flatiron/winston/commit/a5676313b4e9744802cc3b8e1468e4af48830876) dependencies.\n  * Configuration is now [shalow cloned](https://github.com/flatiron/winston/commit/08fccc81d18536d33050496102d98bde648853f2).\n  * [Added logstash support](https://github.com/flatiron/winston/pull/445/files)\n  * Fix for [\"flush\" event should always fire after \"flush\" call bug](https://github.com/flatiron/winston/pull/446/files)\n  * Added tests for file: [open and stress](https://github.com/flatiron/winston/commit/47d885797a2dd0d3cd879305ca813a0bd951c378).\n  * [Test fixes](https://github.com/flatiron/winston/commit/9e39150e0018f43d198ca4c160acef2af9860bf4)\n  * [Fix \")\" on string interpolation](https://github.com/flatiron/winston/pull/394/files)\n\n## 0.6.2 / 2012-07-08\n\n  * Added prettyPrint option for console logging\n  * Multi-line values for conditional returns are not allowed\n  * Added acceptance of `stringify` option\n  * Fixed padding for log levels\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, gender identity and expression, level of experience,\neducation, socio-economic status, nationality, personal appearance, race,\nreligion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\n  advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n  address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at charlie.robbins@gmail.com. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# CONTRIBUTING\nPLEASE NOTE: This document has not been updated in a while and is out of date, but contents are retained as some may still be useful.\n\nTL;DR? The `winston` project recently shipped `3.0.0` out of RC and is actively\nworking towards the next feature release as it continues to triage issues. \n\n- [Be kind & actively empathetic to one another](CODE_OF_CONDUCT.md)\n- [What makes up `winston`?](#what-makes-up-winston)\n- [What about `winston@2.x`?!](#what-about-winston-2.x)\n- [Could this be implemented as a format?](#could-this-be-implemented-as-a-format)\n- [Roadmap](#roadmap)\n\nLooking for somewhere to help? Checkout the [Roadmap](#roadmap) & help triage open issues! Find an issue that looks like a duplicate? It probably is! Comment on it so we know it's maybe a duplicate 🙏.\n\n## What makes up `winston`?\n\nAs of `winston@3` the project has been broken out into a few modules:\n\n- [winston-transport]: `Transport` stream implementation & legacy `Transport` wrapper.\n- [logform]: All formats exports through `winston.format` \n- `LEVEL` and `MESSAGE` symbols exposed through [triple-beam].\n- [Shared test suite][abstract-winston-transport] for community transports \n\nLet's dig in deeper. The example below has been annotated to demonstrate the different packages that compose the example itself:\n\n``` js\nconst { createLogger, transports, format } = require('winston');\nconst Transport = require('winston-transport');\nconst logform = require('logform');\nconst { combine, timestamp, label, printf } = logform.format;\n\n// winston.format is require('logform')\nconsole.log(logform.format === format) // true\n\nconst logger = createLogger({\n  format: combine(\n    label({ label: 'right meow!' }),\n    timestamp(),\n    printf(({ level, message, label, timestamp }) => {\n      return `${timestamp} [${label}] ${level}: ${message}`;\n    })\n  ),\n  transports: [new transports.Console()]\n});\n```\n\n## What about `winston@2.x`?!\n\n> _If you are opening an issue regarding the `2.x` release-line please know\n> that 2.x work has ceased. The `winston` team will review PRs that fix\n> issues, but as issues are opened we will close them._\n\nYou will commonly see this closing `winston@2.x` issues:\n\n```\nDevelopment `winston@2.x` has ceased. Please consider upgrading to\n`winston@3.0.0`. If you feel strongly about this bug please open a PR against\nthe `2.x` branch. Thank you for using `winston`!\n```\n\n## Could this be implemented as a format?\n\nBefore opening issues for new features consider if this feature could be implemented as a [custom format]. If it is, you will see your issue closed with this message:\n\n```\nThis can be accomplished with using [custom formats](https://github.com/winstonjs/winston#creating-custom-formats) in `winston@3.0.0`. Please consider upgrading.\n```\n\n# Roadmap\n\nBelow is the list of items that make up the roadmap through `3.4.0`. We are actively triaging the open issues, so it is likely a few more critical path items will be added to this list before the next release goes out.\n\n- [Version 3.3.0](#version-320)\n- [Version 3.4.0](#version-330)\n- [Version 3.5.0](#version-340)\n\n## Legend\n\n- [ ] Unstarted work.\n- [x] Finished work.\n- [-] Partially finished or in-progress work. \n\n## Version `3.3.0`\n\n### High priority issues (non-blocking)\n- [ ] Move `File` transport into `winston-file`.\n- [Browser support](https://github.com/winstonjs/winston/issues/287)\n  - [ ] Unit tests for `webpack` & `rollup` \n  - [ ] Replicate browser-only transpilation for `winston`, `winston-transport`, `triple-beam`.\n- [-] Full JSDoc coverage\n- Benchmarking for `File` and `Stream` transports:\n   - [x] Benchmarking integration in `pino`.\n   - [x] Upgrade `pino` to latest `winston`.\n   - See: https://github.com/winstonjs/logmark\n   - See also: https://github.com/pinojs/pino/pull/232\n- [ ] Move `logged` event into `winston-transport` to remove need for it in each individual Transport written _or remove the `logged` event entirely._\n\n### Increased code & scenario coverage\n- [-] Replace all `vows`-based tests.\n  - [-] `test/transports/*-test.js` \n- [ ] Code coverage tests above 80% for `winston` _(currently `~70%`)_.\n  - [-] Core scenarios covered in `abstract-winston-transport`.\n  - [-] Full integration tests for all `logform` transports\n\n### Communications / Compatibility\n- [ ] `README.md` for `winston-compat`.\n- [ ] Update all transports documented in `docs/transports.md` for `winston@3`.\n\n## Version `3.4.0`\n\n### Querying, Streaming, Uncaught Exceptions\n- [-] Streaming\n\n### Communications / Compatibility\n- [ ] `winstonjs.org` documentation site.\n\n## Version `3.5.0`\n\n### Querying, Streaming, Uncaught Exceptions\n- [-] Querying\n\n[winston-transport]: https://github.com/winstonjs/winston-transport\n[logform]: https://github.com/winstonjs/logform\n[triple-beam]: https://github.com/winstonjs/triple-beam\n[abstract-winston-transport]: https://github.com/winstonjs/abstract-winston-transport\n[stress-test]: https://github.com/winstonjs/winston/blob/master/test/transports/file-stress.test.js\n[custom format]: https://github.com/winstonjs/winston#creating-custom-formats\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2010 Charlie Robbins\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE."
  },
  {
    "path": "README.md",
    "content": "# winston\n\nA logger for just about everything.\n\n[![Version npm](https://img.shields.io/npm/v/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston)\n[![npm Downloads](https://img.shields.io/npm/dm/winston.svg?style=flat-square)](https://npmcharts.com/compare/winston?minimal=true)\n[![build status](https://github.com/winstonjs/winston/actions/workflows/ci.yml/badge.svg)](https://github.com/winstonjs/winston/actions/workflows/ci.yml)\n[![coverage status](https://coveralls.io/repos/github/winstonjs/winston/badge.svg?branch=master)](https://coveralls.io/github/winstonjs/winston?branch=master)\n\n[![NPM](https://nodei.co/npm/winston.png?downloads=true&downloadRank=true)](https://nodei.co/npm/winston/)\n\n## winston@3\n\nSee the [Upgrade Guide](UPGRADE-3.0.md) for more information. Bug reports and\nPRs welcome!\n\n## Looking for `winston@2.x` documentation?\n\nPlease note that the documentation below is for `winston@3`.\n[Read the `winston@2.x` documentation].\n\n## Motivation\n\n`winston` is designed to be a simple and universal logging library with\nsupport for multiple transports. A transport is essentially a storage device\nfor your logs. Each `winston` logger can have multiple transports (see:\n[Transports]) configured at different levels (see: [Logging levels]). For\nexample, one may want error logs to be stored in a persistent remote location\n(like a database), but all logs output to the console or a local file.\n\n`winston` aims to decouple parts of the logging process to make it more\nflexible and extensible. Attention is given to supporting flexibility in log\nformatting (see: [Formats]) & levels (see: [Using custom logging levels]), and\nensuring those APIs decoupled from the implementation of transport logging\n(i.e. how the logs are stored / indexed, see: [Adding Custom Transports]) to\nthe API that they exposed to the programmer.\n\n## Quick Start\n\nTL;DR? Check out the [quick start example][quick-example] in `./examples/`.\nThere are a number of other examples in [`./examples/*.js`][examples].\nDon't see an example you think should be there? Submit a pull request\nto add it!\n\n## Usage\n\nThe recommended way to use `winston` is to create your own logger. The\nsimplest way to do this is using `winston.createLogger`:\n\n``` js\nconst winston = require('winston');\n\nconst logger = winston.createLogger({\n  level: 'info',\n  format: winston.format.json(),\n  defaultMeta: { service: 'user-service' },\n  transports: [\n    //\n    // - Write all logs with importance level of `error` or higher to `error.log`\n    //   (i.e., error, fatal, but not other levels)\n    //\n    new winston.transports.File({ filename: 'error.log', level: 'error' }),\n    //\n    // - Write all logs with importance level of `info` or higher to `combined.log`\n    //   (i.e., fatal, error, warn, and info, but not trace)\n    //\n    new winston.transports.File({ filename: 'combined.log' }),\n  ],\n});\n\n//\n// If we're not in production then log to the `console` with the format:\n// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `\n//\nif (process.env.NODE_ENV !== 'production') {\n  logger.add(new winston.transports.Console({\n    format: winston.format.simple(),\n  }));\n}\n```\n\nYou may also log directly via the default logger exposed by\n`require('winston')`, but this merely intended to be a convenient shared\nlogger to use throughout your application if you so choose.\nNote that the default logger doesn't have any transports by default.\nYou need add transports by yourself, and leaving the default logger without any\ntransports may produce a high memory usage issue.\n\n## Table of contents\n\n* [Motivation](#motivation)\n* [Quick Start](#quick-start)\n* [Usage](#usage)\n* [Table of Contents](#table-of-contents)\n* [Logging](#logging)\n  * [Creating your logger](#creating-your-own-logger)\n  * [Streams, `objectMode`, and `info` objects](#streams-objectmode-and-info-objects)\n* [Formats]\n  * [Combining formats](#combining-formats)\n  * [String interpolation](#string-interpolation)\n  * [Filtering `info` Objects](#filtering-info-objects)\n  * [Creating custom formats](#creating-custom-formats)\n* [Logging levels]\n  * [Using logging levels](#using-logging-levels)\n  * [Using custom logging levels](#using-custom-logging-levels)\n* [Transports]\n  * [Multiple transports of the same type](#multiple-transports-of-the-same-type)\n  * [Adding Custom Transports](#adding-custom-transports)\n  * [Common Transport options](#common-transport-options)\n* [Exceptions](#exceptions)\n  * [Handling Uncaught Exceptions with winston](#handling-uncaught-exceptions-with-winston)\n  * [To Exit or Not to Exit](#to-exit-or-not-to-exit)\n* [Rejections](#rejections)\n  * [Handling Uncaught Promise Rejections with winston](#handling-uncaught-promise-rejections-with-winston)\n* [Profiling](#profiling)\n* [Streaming Logs](#streaming-logs)\n* [Querying Logs](#querying-logs)\n* [Further Reading](#further-reading)\n  * [Using the default logger](#using-the-default-logger)\n  * [Awaiting logs to be written in `winston`](#awaiting-logs-to-be-written-in-winston)\n  * [Working with multiple Loggers in `winston`](#working-with-multiple-loggers-in-winston)\n  * [Routing Console transport messages to the console instead of stdout and stderr](#routing-console-transport-messages-to-the-console-instead-of-stdout-and-stderr)\n* [Installation](#installation)\n* [Run Tests](#run-tests)\n\n## Logging\n\nLogging levels in `winston` conform to the severity ordering specified by\n[RFC5424]: _severity of all levels is assumed to be numerically **ascending**\nfrom most important to least important._\n\n``` js\nconst levels = {\n  error: 0,\n  warn: 1,\n  info: 2,\n  http: 3,\n  verbose: 4,\n  debug: 5,\n  silly: 6\n};\n```\n\n### Creating your own Logger\nYou get started by creating a logger using `winston.createLogger`:\n\n``` js\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Console(),\n    new winston.transports.File({ filename: 'combined.log' })\n  ]\n});\n```\n\nA logger accepts the following parameters:\n\n| Name          | Default                     |  Description    |\n| ------------- | --------------------------- | --------------- |\n| `level`       | `'info'`                    | Log only if [`info.level`](#streams-objectmode-and-info-objects) is less than or equal to this level  |\n| `levels`      | `winston.config.npm.levels` | Levels (and colors) representing log priorities            |\n| `format`      | `winston.format.json`       | Formatting for `info` messages  (see: [Formats])           |\n| `transports`  | `[]` _(No transports)_      | Set of logging targets for `info` messages                 |\n| `exitOnError` | `true`                      | If false, handled exceptions will not cause `process.exit` |\n| `silent`      | `false`                     | If true, all logs are suppressed |\n\nThe levels provided to `createLogger` will be defined as convenience methods\non the `logger` returned.\n\n``` js\n//\n// Logging\n//\nlogger.log({\n  level: 'info',\n  message: 'Hello distributed log files!'\n});\n\nlogger.info('Hello again distributed logs');\n```\n\nYou can add or remove transports from the `logger` once it has been provided\nto you from `winston.createLogger`:\n\n``` js\nconst files = new winston.transports.File({ filename: 'combined.log' });\nconst console = new winston.transports.Console();\n\nlogger\n  .clear()          // Remove all transports\n  .add(console)     // Add console transport\n  .add(files)       // Add file transport\n  .remove(console); // Remove console transport\n```\n\nYou can also wholesale reconfigure a `winston.Logger` instance using the\n`configure` method:\n\n``` js\nconst logger = winston.createLogger({\n  level: 'info',\n  transports: [\n    new winston.transports.Console(),\n    new winston.transports.File({ filename: 'combined.log' })\n  ]\n});\n\n//\n// Replaces the previous transports with those in the\n// new configuration wholesale.\n//\nconst DailyRotateFile = require('winston-daily-rotate-file');\nlogger.configure({\n  level: 'verbose',\n  transports: [\n    new DailyRotateFile(opts)\n  ]\n});\n```\n\n### Creating child loggers\n\nYou can create child loggers from existing loggers to pass metadata overrides:\n\n``` js\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Console(),\n  ]\n});\n\nconst childLogger = logger.child({ requestId: '451' });\n```\n> `.child` is likely to be bugged if you're also extending the `Logger` class, due to some implementation details that make `this` keyword to point to unexpected things. Use with caution.\n\n### Streams, `objectMode`, and `info` objects\n\nIn `winston`, both `Logger` and `Transport` instances are treated as\n[`objectMode`](https://nodejs.org/api/stream.html#stream_object_mode)\nstreams that accept an `info` object.\n\nThe `info` parameter provided to a given format represents a single log\nmessage. The object itself is mutable. Every `info` must have at least the\n`level` and `message` properties:\n\n``` js\nconst info = {\n  level: 'info',                 // Level of the logging message\n  message: 'Hey! Log something?' // Descriptive message being logged.\n};\n```\n\nProperties **besides level and message** are considered as \"`meta`\". i.e.:\n\n``` js\nconst { level, message, ...meta } = info;\n```\n\nSeveral of the formats in `logform` itself add additional properties:\n\n| Property    | Format added by | Description |\n| ----------- | --------------- | ----------- |\n| `splat`     | `splat()`       | String interpolation splat for `%d %s`-style messages. |\n| `timestamp` | `timestamp()`   |  timestamp the message was received. |\n| `label`     | `label()`       | Custom label associated with each message. |\n| `ms`        | `ms()`          | Number of milliseconds since the previous log message. |\n\nAs a consumer you may add whatever properties you wish – _internal state is\nmaintained by `Symbol` properties:_\n\n- `Symbol.for('level')` _**(READ-ONLY)**:_ equal to `level` property.\n  **Is treated as immutable by all code.**\n- `Symbol.for('message'):` complete string message set by \"finalizing formats\":\n  - `json`\n  - `logstash`\n  - `printf`\n  - `prettyPrint`\n  - `simple`\n- `Symbol.for('splat')`: additional string interpolation arguments. _Used\n  exclusively by `splat()` format._\n\nThese Symbols are stored in another package: `triple-beam` so that all\nconsumers of `logform` can have the same Symbol reference. i.e.:\n\n``` js\nconst { LEVEL, MESSAGE, SPLAT } = require('triple-beam');\n\nconsole.log(LEVEL === Symbol.for('level'));\n// true\n\nconsole.log(MESSAGE === Symbol.for('message'));\n// true\n\nconsole.log(SPLAT === Symbol.for('splat'));\n// true\n```\n\n> **NOTE:** any `{ message }` property in a `meta` object provided will\n> automatically be concatenated to any `msg` already provided: For\n> example the below will concatenate 'world' onto 'hello':\n>\n> ``` js\n> logger.log('error', 'hello', { message: 'world' });\n> logger.info('hello', { message: 'world' });\n> ```\n\n## Formats\n\nFormats in `winston` can be accessed from `winston.format`. They are\nimplemented in [`logform`](https://github.com/winstonjs/logform), a separate\nmodule from `winston`. This allows flexibility when writing your own transports\nin case you wish to include a default format with your transport.\n\nIn modern versions of `node` template strings are very performant and are the\nrecommended way for doing most end-user formatting. If you want to bespoke\nformat your logs, `winston.format.printf` is for you:\n\n``` js\nconst { createLogger, format, transports } = require('winston');\nconst { combine, timestamp, label, printf } = format;\n\nconst myFormat = printf(({ level, message, label, timestamp }) => {\n  return `${timestamp} [${label}] ${level}: ${message}`;\n});\n\nconst logger = createLogger({\n  format: combine(\n    label({ label: 'right meow!' }),\n    timestamp(),\n    myFormat\n  ),\n  transports: [new transports.Console()]\n});\n```\n\nTo see what built-in formats are available and learn more about creating your\nown custom logging formats, see [`logform`][logform].\n\n### Combining formats\n\nAny number of formats may be combined into a single format using\n`format.combine`. Since `format.combine` takes no `opts`, as a convenience it\nreturns pre-created instance of the combined format.\n\n``` js\nconst { createLogger, format, transports } = require('winston');\nconst { combine, timestamp, label, prettyPrint } = format;\n\nconst logger = createLogger({\n  format: combine(\n    label({ label: 'right meow!' }),\n    timestamp(),\n    prettyPrint()\n  ),\n  transports: [new transports.Console()]\n})\n\nlogger.log({\n  level: 'info',\n  message: 'What time is the testing at?'\n});\n// Outputs:\n// { level: 'info',\n//   message: 'What time is the testing at?',\n//   label: 'right meow!',\n//   timestamp: '2017-09-30T03:57:26.875Z' }\n```\n\n### String interpolation\n\nThe `log` method provides the string interpolation using [util.format]. **It\nmust be enabled using `format.splat()`.**\n\nBelow is an example that defines a format with string interpolation of\nmessages using `format.splat` and then serializes the entire `info` message\nusing `format.simple`.\n\n``` js\nconst { createLogger, format, transports } = require('winston');\nconst logger = createLogger({\n  format: format.combine(\n    format.splat(),\n    format.simple()\n  ),\n  transports: [new transports.Console()]\n});\n\n// info: test message my string {}\nlogger.log('info', 'test message %s', 'my string');\n\n// info: test message 123 {}\nlogger.log('info', 'test message %d', 123);\n\n// info: test message first second {number: 123}\nlogger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 });\n```\n\n### Filtering `info` Objects\n\nIf you wish to filter out a given `info` Object completely when logging then\nsimply return a falsey value.\n\n``` js\nconst { createLogger, format, transports } = require('winston');\n\n// Ignore log messages if they have { private: true }\nconst ignorePrivate = format((info, opts) => {\n  if (info.private) { return false; }\n  return info;\n});\n\nconst logger = createLogger({\n  format: format.combine(\n    ignorePrivate(),\n    format.json()\n  ),\n  transports: [new transports.Console()]\n});\n\n// Outputs: {\"level\":\"error\",\"message\":\"Public error to share\"}\nlogger.log({\n  level: 'error',\n  message: 'Public error to share'\n});\n\n// Messages with { private: true } will not be written when logged.\nlogger.log({\n  private: true,\n  level: 'error',\n  message: 'This is super secret - hide it.'\n});\n```\n\nUse of `format.combine` will respect any falsey values return and stop\nevaluation of later formats in the series. For example:\n\n``` js\nconst { format } = require('winston');\nconst { combine, timestamp, label } = format;\n\nconst willNeverThrow = format.combine(\n  format(info => { return false })(), // Ignores everything\n  format(info => { throw new Error('Never reached') })()\n);\n```\n\n### Creating custom formats\n\nFormats are prototypal objects (i.e. class instances) that define a single\nmethod: `transform(info, opts)` and return the mutated `info`:\n\n- `info`: an object representing the log message.\n- `opts`: setting specific to the current instance of the format.\n\nThey are expected to return one of two things:\n\n- **An `info` Object** representing the modified `info` argument. Object\nreferences need not be preserved if immutability is preferred. All current\nbuilt-in formats consider `info` mutable, but [immutablejs] is being\nconsidered for future releases.\n- **A falsey value** indicating that the `info` argument should be ignored by the\ncaller. (See: [Filtering `info` Objects](#filtering-info-objects)) below.\n\n`winston.format` is designed to be as simple as possible. To define a new\nformat, simply pass it a `transform(info, opts)` function to get a new\n`Format`.\n\nThe named `Format` returned can be used to create as many copies of the given\n`Format` as desired:\n\n``` js\nconst { format } = require('winston');\n\nconst volume = format((info, opts) => {\n  if (opts.yell) {\n    info.message = info.message.toUpperCase();\n  } else if (opts.whisper) {\n    info.message = info.message.toLowerCase();\n  }\n\n  return info;\n});\n\n// `volume` is now a function that returns instances of the format.\nconst scream = volume({ yell: true });\nconsole.dir(scream.transform({\n  level: 'info',\n  message: `sorry for making you YELL in your head!`\n}, scream.options));\n// {\n//   level: 'info'\n//   message: 'SORRY FOR MAKING YOU YELL IN YOUR HEAD!'\n// }\n\n// `volume` can be used multiple times to create different formats.\nconst whisper = volume({ whisper: true });\nconsole.dir(whisper.transform({\n  level: 'info',\n  message: `WHY ARE THEY MAKING US YELL SO MUCH!`\n}, whisper.options));\n// {\n//   level: 'info'\n//   message: 'why are they making us yell so much!'\n// }\n```\n\n## Logging Levels\n\nLogging levels in `winston` conform to the severity ordering specified by\n[RFC5424]: _severity of all levels is assumed to be numerically **ascending**\nfrom most important to least important._\n\nEach `level` is given a specific integer priority. The higher the priority the\nmore important the message is considered to be, and the lower the\ncorresponding integer priority.  For example, as specified exactly in RFC5424\nthe `syslog` levels are prioritized from 0 to 7 (highest to lowest).\n\n```js\n{\n  emerg: 0,\n  alert: 1,\n  crit: 2,\n  error: 3,\n  warning: 4,\n  notice: 5,\n  info: 6,\n  debug: 7\n}\n```\n\nSimilarly, `npm` logging levels are prioritized from 0 to 6 (highest to\nlowest):\n\n``` js\n{\n  error: 0,\n  warn: 1,\n  info: 2,\n  http: 3,\n  verbose: 4,\n  debug: 5,\n  silly: 6\n}\n```\n\nIf you do not explicitly define the levels that `winston` should use, the\n`npm` levels above will be used.\n\n### Using Logging Levels\n\nSetting the level for your logging message can be accomplished in one of two\nways. You can pass a string representing the logging level to the log() method\nor use the level specified methods defined on every winston Logger.\n\n``` js\n//\n// Any logger instance\n//\nlogger.log('silly', \"127.0.0.1 - there's no place like home\");\nlogger.log('debug', \"127.0.0.1 - there's no place like home\");\nlogger.log('verbose', \"127.0.0.1 - there's no place like home\");\nlogger.log('info', \"127.0.0.1 - there's no place like home\");\nlogger.log('warn', \"127.0.0.1 - there's no place like home\");\nlogger.log('error', \"127.0.0.1 - there's no place like home\");\nlogger.info(\"127.0.0.1 - there's no place like home\");\nlogger.warn(\"127.0.0.1 - there's no place like home\");\nlogger.error(\"127.0.0.1 - there's no place like home\");\n\n//\n// Default logger\n//\nwinston.log('info', \"127.0.0.1 - there's no place like home\");\nwinston.info(\"127.0.0.1 - there's no place like home\");\n```\n\n`winston` allows you to define a `level` property on each transport which\nspecifies the **maximum** level of messages that a transport should log. For\nexample, using the `syslog` levels you could log only `error` messages to the\nconsole and everything `info` and below to a file (which includes `error`\nmessages):\n\n``` js\nconst logger = winston.createLogger({\n  levels: winston.config.syslog.levels,\n  transports: [\n    new winston.transports.Console({ level: 'error' }),\n    new winston.transports.File({\n      filename: 'combined.log',\n      level: 'info'\n    })\n  ]\n});\n```\n\nYou may also dynamically change the log level of a transport:\n\n``` js\nconst transports = {\n  console: new winston.transports.Console({ level: 'warn' }),\n  file: new winston.transports.File({ filename: 'combined.log', level: 'error' })\n};\n\nconst logger = winston.createLogger({\n  transports: [\n    transports.console,\n    transports.file\n  ]\n});\n\nlogger.info('Will not be logged in either transport!');\ntransports.console.level = 'info';\ntransports.file.level = 'info';\nlogger.info('Will be logged in both transports!');\n```\n\n`winston` supports customizable logging levels, defaulting to npm style\nlogging levels. Levels must be specified at the time of creating your logger.\n\n### Using Custom Logging Levels\n\nIn addition to the predefined `npm`, `syslog`, and `cli` levels available in\n`winston`, you can also choose to define your own:\n\n``` js\nconst myCustomLevels = {\n  levels: {\n    foo: 0,\n    bar: 1,\n    baz: 2,\n    foobar: 3\n  },\n  colors: {\n    foo: 'blue',\n    bar: 'green',\n    baz: 'yellow',\n    foobar: 'red'\n  }\n};\n\nconst customLevelLogger = winston.createLogger({\n  levels: myCustomLevels.levels\n});\n\ncustomLevelLogger.foobar('some foobar level-ed message');\n```\n\nAlthough there is slight repetition in this data structure, it enables simple\nencapsulation if you do not want to have colors. If you do wish to have\ncolors, in addition to passing the levels to the Logger itself, you must make\nwinston aware of them:\n\n``` js\nwinston.addColors(myCustomLevels.colors);\n```\n\nThis enables loggers using the `colorize` formatter to appropriately color and style\nthe output of custom levels.\n\nAdditionally, you can also change background color and font style.\nFor example,\n``` js\nbaz: 'italic yellow',\nfoobar: 'bold red cyanBG'\n```\n\nPossible options are below.\n\n* Font styles: `bold`, `dim`, `italic`, `underline`, `inverse`, `hidden`,\n  `strikethrough`.\n\n* Font foreground colors: `black`, `red`, `green`, `yellow`, `blue`, `magenta`,\n  `cyan`, `white`, `gray`, `grey`.\n\n* Background colors: `blackBG`, `redBG`, `greenBG`, `yellowBG`, `blueBG`\n  `magentaBG`, `cyanBG`, `whiteBG`\n\n### Colorizing Standard logging levels\n\nTo colorize the standard logging level add\n```js\nwinston.format.combine(\n  winston.format.colorize(),\n  winston.format.simple()\n);\n```\nwhere `winston.format.simple()` is whatever other formatter you want to use.  The `colorize` formatter must come before any formatters adding text you wish to color.\n\n### Colorizing full log line when json formatting logs\n\nTo colorize the full log line with the json formatter you can apply the following\n\n```js\nwinston.format.combine(\n  winston.format.json(),\n  winston.format.colorize({ all: true })\n);\n```\n\n## Transports\n\nThere are several [core transports] included in  `winston`, which leverage the\nbuilt-in networking and file I/O offered by Node.js core. In addition, there\nare [additional transports] written by members of the community.\n\n## Multiple transports of the same type\n\nIt is possible to use multiple transports of the same type e.g.\n`winston.transports.File` when you construct the transport.\n\n``` js\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.File({\n      filename: 'combined.log',\n      level: 'info'\n    }),\n    new winston.transports.File({\n      filename: 'errors.log',\n      level: 'error'\n    })\n  ]\n});\n```\n\nIf you later want to remove one of these transports you can do so by using the\ntransport itself. e.g.:\n\n``` js\nconst combinedLogs = logger.transports.find(transport => {\n  return transport.filename === 'combined.log'\n});\n\nlogger.remove(combinedLogs);\n```\n\n## Adding Custom Transports\n\nAdding a custom transport is easy. All you need to do is accept any options\nyou need, implement a log() method, and consume it with `winston`.\n\n``` js\nconst Transport = require('winston-transport');\nconst util = require('util');\n\n//\n// Inherit from `winston-transport` so you can take advantage\n// of the base functionality and `.exceptions.handle()`.\n//\nmodule.exports = class YourCustomTransport extends Transport {\n  constructor(opts) {\n    super(opts);\n    //\n    // Consume any custom options here. e.g.:\n    // - Connection information for databases\n    // - Authentication information for APIs (e.g. loggly, papertrail,\n    //   logentries, etc.).\n    //\n  }\n\n  log(info, callback) {\n    setImmediate(() => {\n      this.emit('logged', info);\n    });\n\n    // Perform the writing to the remote service\n    callback();\n  }\n};\n```\n\n## Common Transport options\n\nAs every transport inherits from [winston-transport], it's possible to set\na custom format and a custom log level on each transport separately:\n\n``` js\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.File({\n      filename: 'error.log',\n      level: 'error',\n      format: winston.format.json()\n    }),\n    new winston.transports.Http({\n      level: 'warn',\n      format: winston.format.json()\n    }),\n    new winston.transports.Console({\n      level: 'info',\n      format: winston.format.combine(\n        winston.format.colorize(),\n        winston.format.simple()\n      )\n    })\n  ]\n});\n```\n\n## Exceptions\n\n### Handling Uncaught Exceptions with winston\n\nWith `winston`, it is possible to catch and log `uncaughtException` events\nfrom your process. With your own logger instance you can enable this behavior\nwhen it's created or later on in your applications lifecycle:\n\n``` js\nconst { createLogger, transports } = require('winston');\n\n// Enable exception handling when you create your logger.\nconst logger = createLogger({\n  transports: [\n    new transports.File({ filename: 'combined.log' })\n  ],\n  exceptionHandlers: [\n    new transports.File({ filename: 'exceptions.log' })\n  ]\n});\n\n// Or enable it later on by adding a transport or using `.exceptions.handle`\nconst logger = createLogger({\n  transports: [\n    new transports.File({ filename: 'combined.log' })\n  ]\n});\n\n// Call exceptions.handle with a transport to handle exceptions\nlogger.exceptions.handle(\n  new transports.File({ filename: 'exceptions.log' })\n);\n```\n\nIf you want to use this feature with the default logger, simply call\n`.exceptions.handle()` with a transport instance.\n\n``` js\n//\n// You can add a separate exception logger by passing it to `.exceptions.handle`\n//\nwinston.exceptions.handle(\n  new winston.transports.File({ filename: 'path/to/exceptions.log' })\n);\n\n//\n// Alternatively you can set `handleExceptions` to true when adding transports\n// to winston.\n//\nwinston.add(new winston.transports.File({\n  filename: 'path/to/combined.log',\n  handleExceptions: true\n}));\n```\n\n### To Exit or Not to Exit\n\nBy default, winston will exit after logging an uncaughtException. If this is\nnot the behavior you want, set `exitOnError = false`\n\n``` js\nconst logger = winston.createLogger({ exitOnError: false });\n\n//\n// or, like this:\n//\nlogger.exitOnError = false;\n```\n\nWhen working with custom logger instances, you can pass in separate transports\nto the `exceptionHandlers` property or set `handleExceptions` on any\ntransport.\n\n##### Example 1\n\n``` js\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.File({ filename: 'path/to/combined.log' })\n  ],\n  exceptionHandlers: [\n    new winston.transports.File({ filename: 'path/to/exceptions.log' })\n  ]\n});\n```\n\n##### Example 2\n\n``` js\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Console({\n      handleExceptions: true\n    })\n  ],\n  exitOnError: false\n});\n```\n\nThe `exitOnError` option can also be a function to prevent exit on only\ncertain types of errors:\n\n``` js\nfunction ignoreEpipe(err) {\n  return err.code !== 'EPIPE';\n}\n\nconst logger = winston.createLogger({ exitOnError: ignoreEpipe });\n\n//\n// or, like this:\n//\nlogger.exitOnError = ignoreEpipe;\n```\n\n## Rejections\n\n### Handling Uncaught Promise Rejections with winston\n\nWith `winston`, it is possible to catch and log `unhandledRejection` events\nfrom your process. With your own logger instance you can enable this behavior\nwhen it's created or later on in your applications lifecycle:\n\n``` js\nconst { createLogger, transports } = require('winston');\n\n// Enable rejection handling when you create your logger.\nconst logger = createLogger({\n  transports: [\n    new transports.File({ filename: 'combined.log' })\n  ],\n  rejectionHandlers: [\n    new transports.File({ filename: 'rejections.log' })\n  ]\n});\n\n// Or enable it later on by adding a transport or using `.rejections.handle`\nconst logger = createLogger({\n  transports: [\n    new transports.File({ filename: 'combined.log' })\n  ]\n});\n\n// Call rejections.handle with a transport to handle rejections\nlogger.rejections.handle(\n  new transports.File({ filename: 'rejections.log' })\n);\n```\n\nIf you want to use this feature with the default logger, simply call\n`.rejections.handle()` with a transport instance.\n\n``` js\n//\n// You can add a separate rejection logger by passing it to `.rejections.handle`\n//\nwinston.rejections.handle(\n  new winston.transports.File({ filename: 'path/to/rejections.log' })\n);\n\n//\n// Alternatively you can set `handleRejections` to true when adding transports\n// to winston.\n//\nwinston.add(new winston.transports.File({\n  filename: 'path/to/combined.log',\n  handleRejections: true\n}));\n```\n\n## Profiling\n\nIn addition to logging messages and metadata, `winston` also has a simple\nprofiling mechanism implemented for any logger:\n\n``` js\n//\n// Start profile of 'test'\n//\nlogger.profile('test');\n\nsetTimeout(function () {\n  //\n  // Stop profile of 'test'. Logging will now take place:\n  //   '17 Jan 21:00:00 - info: test duration=1000ms'\n  //\n  logger.profile('test');\n}, 1000);\n```\n\nAlso you can start a timer and keep a reference that you can call `.done()`\non:\n\n``` js\n // Returns an object corresponding to a specific timing. When done\n // is called the timer will finish and log the duration. e.g.:\n //\n const profiler = logger.startTimer();\n setTimeout(function () {\n   profiler.done({ message: 'Logging message' });\n }, 1000);\n```\n\nAll profile messages are set to 'info' level by default, and both message and\nmetadata are optional.  For individual profile messages, you can override the default log level by supplying a metadata object with a `level` property:\n\n```js\nlogger.profile('test', { level: 'debug' });\n```\n\n## Querying Logs\n\n`winston` supports querying of logs with Loggly-like options. [See Loggly\nSearch API](https://www.loggly.com/docs/api-retrieving-data/). Specifically:\n`File`, `Couchdb`, `Redis`, `Loggly`, `Nssocket`, and `Http`.\n\n``` js\nconst options = {\n  from: new Date() - (24 * 60 * 60 * 1000),\n  until: new Date(),\n  limit: 10,\n  start: 0,\n  order: 'desc',\n  fields: ['message']\n};\n\n//\n// Find items logged between today and yesterday.\n//\nlogger.query(options, function (err, results) {\n  if (err) {\n    /* TODO: handle me */\n    throw err;\n  }\n\n  console.log(results);\n});\n```\n\n## Streaming Logs\nStreaming allows you to stream your logs back from your chosen transport.\n\n``` js\n//\n// Start at the end.\n//\nwinston.stream({ start: -1 }).on('log', function(log) {\n  console.log(log);\n});\n```\n\n## Further Reading\n\n### Using the Default Logger\n\nThe default logger is accessible through the `winston` module directly. Any\nmethod that you could call on an instance of a logger is available on the\ndefault logger:\n\n``` js\nconst winston = require('winston');\n\nwinston.log('info', 'Hello distributed log files!');\nwinston.info('Hello again distributed logs');\n\nwinston.level = 'debug';\nwinston.log('debug', 'Now my debug messages are written to console!');\n```\n\nBy default, no transports are set on the default logger. You must\nadd or remove transports via the `add()` and `remove()` methods:\n\n``` js\nconst files = new winston.transports.File({ filename: 'combined.log' });\nconst console = new winston.transports.Console();\n\nwinston.add(console);\nwinston.add(files);\nwinston.remove(console);\n```\n\nOr do it with one call to configure():\n\n``` js\nwinston.configure({\n  transports: [\n    new winston.transports.File({ filename: 'somefile.log' })\n  ]\n});\n```\n\nFor more documentation about working with each individual transport supported\nby `winston` see the [`winston` Transports](docs/transports.md) document.\n\n### Awaiting logs to be written in `winston`\n\nOften it is useful to wait for your logs to be written before exiting the\nprocess. Each instance of `winston.Logger` is also a [Node.js stream]. A\n`finish` event will be raised when all logs have flushed to all transports\nafter the stream has been ended.\n\n``` js\nconst transport = new winston.transports.Console();\nconst logger = winston.createLogger({\n  transports: [transport]\n});\n\nlogger.on('finish', function (info) {\n  // All `info` log messages has now been logged\n});\n\nlogger.info('CHILL WINSTON!', { seriously: true });\nlogger.end();\n```\n\nIt is also worth mentioning that the logger also emits an 'error' event\nif an error occurs within the logger itself which\nyou should handle or suppress if you don't want unhandled exceptions:\n\n``` js\n//\n// Handle errors originating in the logger itself\n//\nlogger.on('error', function (err) { /* Do Something */ });\n```\n\n### Working with multiple Loggers in winston\n\nOften in larger, more complex, applications it is necessary to have multiple\nlogger instances with different settings. Each logger is responsible for a\ndifferent feature area (or category). This is exposed in `winston` in two\nways: through `winston.loggers` and instances of `winston.Container`. In fact,\n`winston.loggers` is just a predefined instance of `winston.Container`:\n\n``` js\nconst winston = require('winston');\nconst { format } = winston;\nconst { combine, label, json } = format;\n\n//\n// Configure the logger for `category1`\n//\nwinston.loggers.add('category1', {\n  format: combine(\n    label({ label: 'category one' }),\n    json()\n  ),\n  transports: [\n    new winston.transports.Console({ level: 'silly' }),\n    new winston.transports.File({ filename: 'somefile.log' })\n  ]\n});\n\n//\n// Configure the logger for `category2`\n//\nwinston.loggers.add('category2', {\n  format: combine(\n    label({ label: 'category two' }),\n    json()\n  ),\n  transports: [\n    new winston.transports.Http({ host: 'localhost', port:8080 })\n  ]\n});\n```\n\nNow that your loggers are setup, you can require winston _in any file in your\napplication_ and access these pre-configured loggers:\n\n``` js\nconst winston = require('winston');\n\n//\n// Grab your preconfigured loggers\n//\nconst category1 = winston.loggers.get('category1');\nconst category2 = winston.loggers.get('category2');\n\ncategory1.info('logging to file and console transports');\ncategory2.info('logging to http transport');\n```\n\nIf you prefer to manage the `Container` yourself, you can simply instantiate one:\n\n``` js\nconst winston = require('winston');\nconst { format } = winston;\nconst { combine, label, json } = format;\n\nconst container = new winston.Container();\n\ncontainer.add('category1', {\n  format: combine(\n    label({ label: 'category one' }),\n    json()\n  ),\n  transports: [\n    new winston.transports.Console({ level: 'silly' }),\n    new winston.transports.File({ filename: 'somefile.log' })\n  ]\n});\n\nconst category1 = container.get('category1');\ncategory1.info('logging to file and console transports');\n```\n\n### Routing Console transport messages to the console instead of stdout and stderr\n\nBy default the `winston.transports.Console` transport sends messages to `stdout` and `stderr`. This\nis fine in most situations; however, there are some cases where this isn't desirable, including:\n\n- Debugging using VSCode and attaching to, rather than launching, a Node.js process\n- Writing JSON format messages in AWS Lambda\n- Logging during Jest tests with the `--silent` option\n\nTo make the transport log use `console.log()`, `console.warn()` and `console.error()`\ninstead, set the `forceConsole` option to `true`:\n\n```js\nconst logger = winston.createLogger({\n  level: 'info',\n  transports: [new winston.transports.Console({ forceConsole: true })]\n});\n```\n\n## Installation\n\n``` bash\nnpm install winston\n```\n\n``` bash\nyarn add winston\n```\n\n## Run Tests\n\n``` bash\nnpm test # Runs all tests\nnpm run test:unit # Runs all Unit tests with coverage\nnpm run test:integration # Runs all integration tests\nnpm run test:typescript # Runs tests verifying Typescript types\n```\n\nAll of the winston tests are written with [jest]. Assertions use a mix of [assume] and the built-in jest assertion library.\n\n#### Author: [Charlie Robbins]\n#### Contributors: [Jarrett Cruger], [David Hyde], [Chris Alderson], [Jonathon Terry]\n\n[Transports]: #transports\n[Logging levels]: #logging-levels\n[Formats]: #formats\n[Using custom logging levels]: #using-custom-logging-levels\n[Adding Custom Transports]: #adding-custom-transports\n[core transports]: docs/transports.md#winston-core\n[additional transports]: docs/transports.md#additional-transports\n\n[RFC5424]: https://tools.ietf.org/html/rfc5424\n[util.format]: https://nodejs.org/dist/latest/docs/api/util.html#util_util_format_format_args\n[assume]: https://github.com/bigpipe/assume\n[logform]: https://github.com/winstonjs/logform#readme\n[winston-transport]: https://github.com/winstonjs/winston-transport\n[jest]: https://jestjs.io/\n\n[Read the `winston@2.x` documentation]: https://github.com/winstonjs/winston/tree/2.x\n\n[quick-example]: https://github.com/winstonjs/winston/blob/master/examples/quick-start.js\n[examples]: https://github.com/winstonjs/winston/tree/master/examples\n\n[Charlie Robbins]: http://github.com/indexzero\n[Jarrett Cruger]: https://github.com/jcrugzz\n[David Hyde]: https://github.com/dabh\n[Chris Alderson]: https://github.com/chrisalderson\n[Jonathon Terry]: https://github.com/maverick1872\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Reporting a Vulnerability\n\nPlease report security issues to `npm view yadeep maintainers.email`.\n"
  },
  {
    "path": "UPGRADE-3.0.md",
    "content": "# Upgrading to `winston@3.0.0`\n\n> This document represents a **living guide** on upgrading to `winston@3`.\n> Much attention has gone into the details, but if you are having trouble\n> upgrading to `winston@3.0.0` **PLEASE** open an issue so we can improve this\n> guide! \n\n- [Breaking changes]\n   - [Top-level `winston.*` API]\n   - [Transports]\n   - [`winston.Container` and `winston.loggers`]\n   - [`winston.Logger`]\n   - [Exceptions & exception handling]\n   - [Other minor breaking changes]\n- [Upgrading to `winston.format`]\n   - [Removed `winston.Logger` formatting options]\n   - [Removed `winston.transports.{File,Console,Http}` formatting options]\n   - [Migrating `filters` and `rewriters` to `formats` in `winston@3`]\n- [Modularity: `winston-transport`, `logform` and more]\n\n## Breaking changes\n\n### Top-level `winston.*` API\n- `winston.Logger` has been replaced with `winston.createLogger`.\n- `winston.setLevels` has been removed. Levels are frozen at the time of Logger creation.\n- Setting the level on the default `winston` logger no longer sets the level on the transports associated with the default `winston` logger.\n- The default logger exposed by `require('winston')` no longer has default `Console` transports, \nand leaving it without transports may cause a high memory usage issue.\n\n### Transports\n- `winston.transports.Memory` was removed. Use any Node.js `stream.Writeable` with a large `highWaterMark` instance instead.\n- When writing transports use `winston-transport` instead of\n  `winston.Transport`.\n- Many formatting options that were previously configurable on transports \n  (e.g. `json`, `raw`, `colorize`, `prettyPrint`, `timestamp`, `logstash`, \n  `align`) should now be set by adding the appropriate formatter instead.\n  _(See: \"Removed `winston.transports.{File,Console,Http}` formatting options\"\n  below)_ \n- In `winston.transports.Console`, output for all log levels are now sent to stdout by default.\n    - `stderrLevels` option now defaults to `[]`.\n    - `debugStdout` option has been removed.\n\n### `winston.Container` and `winston.loggers`\n- `winston.Container` instances no longer have default `Console` transports.\nFailing to add any transports may cause a high memory usage issue.\n- `winston.Container.prototype.add` no longer does crazy options parsing. Implementation inspired by [segmentio/winston-logger](https://github.com/segmentio/winston-logger/blob/master/lib/index.js#L20-L43)\n\n### `winston.Logger`\n- **Do not use** `new winston.Logger(opts)` – it has been removed for\n  improved performance. Use `winston.createLogger(opts)` instead.\n\n- `winston.Logger.log` and level-specific methods (`.info`, `.error`, etc)\n  **no longer accepts a callback.** The vast majority of use cases for this\n  feature was folks awaiting _all logging_ to complete, not just a single\n  logging message. To accomplish this:\n\n``` js\nlogger.log('info', 'some message');\nlogger.on('finish', () => process.exit());\nlogger.end();\n```\n\n- `winston.Logger.add` no longer accepts prototypes / classes. Pass\n  **an instance of our transport instead.**\n\n``` js\n// DON'T DO THIS. It will no longer work\nlogger.add(winston.transports.Console);\n\n// Do this instead.\nlogger.add(new winston.transports.Console());\n```\n\n- `winston.Logger` will no longer do automatic splat interpolation by default.\n  Be sure to use `format.splat()` to enable this functionality.\n- `winston.Logger` will no longer respond with an error when logging with no\n  transports.\n- `winston.Logger` will no longer respond with an error if the same transports\n  are added twice.\n- `Logger.prototype.stream`\n  - `options.transport` is removed. Use the transport instance on the logger\n    directly.\n- `Logger.prototype.query`\n  - `options.transport` is removed. Use the transport instance on the logger \n    directly.\n- `Logger.paddings` was removed.\n\n### Exceptions & exception handling\n- `winston.exception` has been removed. Use:\n``` js\nconst exception = winston.ExceptionHandler();\n```\n- `humanReadableUnhandledException` is now the default exception format.\n- `.unhandleExceptions()` will no longer modify transports state, merely just add / remove the `process.on('uncaughtException')` handler.\n   - Call close on any explicit `ExceptionHandlers`.\n   - Set `handleExceptions = false` on all transports.\n\n### Other minor breaking changes\n- `winston.hash` was removed.\n- `winston.common.pad` was removed.\n- `winston.common.serialized` was removed (use `winston-compat`).\n- `winston.common.log` was removed (use `winston-compat`).\n- `winston.paddings` was removed.\n\n## Upgrading to `winston.format`\nThe biggest issue with `winston@2` and previous major releases was that any\nnew formatting options required changes to `winston` itself. All formatting is\nnow handled by **formats**. \n\nCustom formats can now be created with no changes to `winston` core.\n_We encourage you to consider a custom format before opening an issue._\n\n### Removed `winston.Logger` formatting options:\n- The default output format is now `format.json()`.\n- `filters`: Use a custom `format`. See: [Filters and Rewriters] below.\n- `rewriters`: Use a custom `format`. See: [Filters and Rewriters] below.\n\n### Removed `winston.transports.{File,Console,Http}` formatting options\n- `stringify`: Use a [custom format].\n- `formatter`: Use a [custom format].\n- `json`: Use `format.json()`.\n- `raw`: Use `format.json()`.\n- `label`: Use `format.label()`.\n- `logstash`: Use `format.logstash()`.\n- `prettyPrint`: Use `format.prettyPrint()` or a [custom format].\n   - `depth` is an option provided to `format.prettyPrint()`.\n- `colorize`: Use `format.colorize()`.\n- `timestamp`: Use `format.timestamp()`.\n- `logstash`: Use `format.logstash()`.\n- `align`: Use `format.align()`.\n- `showLevel`: Use a [custom format].\n\n### Migrating `filters` and `rewriters` to `formats` in `winston@3`\n\nIn `winston@3.x.x` `info` objects are considered mutable. The API _combined\nformatters and rewriters into a single, new concept:_ **formats**. \n\n#### Filters\n\nIf you are looking to upgrade your `filter` behavior please read on. In\n`winston@2.x` this **filter** behavior:\n\n``` js\nconst isSecret = /super secret/;\nconst logger = new winston.Logger(options);\nlogger.filters.push(function(level, msg, meta) {\n  return msg.replace(isSecret, 'su*** se****');\n});\n\n// Outputs: {\"level\":\"error\",\"message\":\"Public error to share\"}\nlogger.error('Public error to share');\n\n// Outputs: {\"level\":\"error\",\"message\":\"This is su*** se**** - hide it.\"}\nlogger.error('This is super secret - hide it.');\n```\n\nCan be modeled as a **custom format** that you combine with other formats:\n\n``` js\nconst { createLogger, format, transports } = require('winston');\n\n// Ignore log messages if the have { private: true }\nconst isSecret = /super secret/;\nconst filterSecret = format((info, opts) => {\n  info.message = info.message.replace(isSecret, 'su*** se****');\n  return info;\n});\n\nconst logger = createLogger({\n  format: format.combine(\n    filterSecret(),\n    format.json()\n  ),\n  transports: [new transports.Console()]\n});\n\n// Outputs: {\"level\":\"error\",\"message\":\"Public error to share\"}\nlogger.log({\n  level: 'error',\n  message: 'Public error to share'\n});\n\n// Outputs: {\"level\":\"error\",\"message\":\"This is su*** se**** - hide it.\"}\nlogger.log({\n  level: 'error',\n  message: 'This is super secret - hide it.'\n});\n```\n\n#### Rewriters\n\nIf you are looking to upgrade your `rewriter` behavior please read on. In\n`winston@2.x` this **rewriter** behavior:\n\n``` js\nconst logger = new winston.Logger(options);\nlogger.rewriters.push(function(level, msg, meta) {\n  if (meta.creditCard) {\n    meta.creditCard = maskCardNumbers(meta.creditCard)\n  }\n\n  return meta;\n});\n\nlogger.info('transaction ok', { creditCard: 123456789012345 });\n```\n\nCan be modeled as a **custom format** that you combine with other formats:\n\n``` js \nconst maskFormat = winston.format(info => {\n  // You can CHANGE existing property values\n  if (info.creditCard) {\n    info.creditCard = maskCardNumbers(info.creditCard);\n  }\n\n  // You can also ADD NEW properties if you wish\n  info.hasCreditCard = !!info.creditCard;\n\n  return info;\n});\n\nconst logger = winston.createLogger({\n  format: winston.format.combine(\n    maskFormat(),\n    winston.format.json()\n  )\n});\n\nlogger.info('transaction ok', { creditCard: 123456789012345 });\n```\n\nSee [examples/format-mutate.js](/examples/format-mutate.js) for a complete\nend-to-end example that covers both filtering and rewriting behavior in\n`winston@2.x`.\n\n## Modularity: `winston-transport`, `logform` and more...\n\nAs of `winston@3.0.0` the project has been broken out into a few modules:\n\n- [winston-transport]: `Transport` stream implementation & legacy `Transport`\n  wrapper.\n- [logform]: All formats exports through `winston.format`. \n- `LEVEL` and `MESSAGE` symbols exposed through [triple-beam].\n- [Shared test suite][abstract-winston-transport] for community transports. \n\nLet's dig in deeper. The example below has been annotated to demonstrate the different packages that compose the example itself:\n\n``` js\nconst { createLogger, transports, format } = require('winston');\nconst Transport = require('winston-transport');\nconst logform = require('logform');\nconst { combine, timestamp, label, printf } = logform.format;\n\n// winston.format is require('logform')\nconsole.log(logform.format === format) // true\n\nconst logger = createLogger({\n  format: combine(\n    label({ label: 'right meow!' }),\n    timestamp(),\n    printf(nfo => {\n      return `${nfo.timestamp} [${nfo.label}] ${nfo.level}: ${nfo.message}`;\n    })\n  ),\n  transports: [new transports.Console()]\n});\n```\n\n[Breaking changes]: #breaking-changes\n[Top-level `winston.*` API]: #top-level-winston-api\n[Transports]: #transports\n[`winston.Container` and `winston.loggers`]: #winstoncontainer-and-winstonloggers\n[`winston.Logger`]: #winstonlogger\n[Exceptions & exception handling]: #exceptions--exception-handling\n[Other minor breaking changes]: #other-minor-breaking-changes\n[Upgrading to `winston.format`]: #upgrading-to-winstonformat\n[Removed `winston.Logger` formatting options]: #removed-winstonlogger-formatting-options\n[Removed `winston.transports.{File,Console,Http}` formatting options]: #removed-winstontransportsfileconsolehttp-formatting-options\n[Migrating `filters` and `rewriters` to `formats` in `winston@3`]: #migrating-filters-and-rewriters-to-formats-in-winston3\n[Modularity: `winston-transport`, `logform` and more]: #modularity-winston-transport-logform-and-more\n\n[Filters and Rewriters]: #migrating-filters-and-rewriters-to-formats-in-winston3\n[custom format]: /README.md#creating-custom-formats\n\n[winston-transport]: https://github.com/winstonjs/winston-transport\n[logform]: https://github.com/winstonjs/logform\n[triple-beam]: https://github.com/winstonjs/triple-beam\n[abstract-winston-transport]: https://github.com/winstonjs/abstract-winston-transport\n\n"
  },
  {
    "path": "docs/publishing.md",
    "content": "The release process here mostly follows along with the [vbump script](https://github.com/indexzero/vbump) that @indexzero wrote several years ago, but the main steps for a release are as follows:\n\n1. Complete merging in any PRs that should be part of the release.\n1. On the [Releases tab](https://github.com/winstonjs/winston/releases) in the GitHub UI, click 'Draft a new release' in the upper right corner.\n1. Under the 'Choose a tag' dropdown, type the name of the new version starting with a v (e.g. `v3.7.0`) and don't forget to click the 'Create new tag on publish' option below (this step is annoyingly easy to miss):\n![image](https://user-images.githubusercontent.com/563406/160644343-69325988-4ca2-4329-93da-e08266269506.png)\n1. Paste the same version number, with or without the v (with is probably better) in the release title box.\n1. Click 'Generate release notes' and cut & paste the draft contents into the changelog.\n1. Paste the contents of the changelog for this release in the 'Describe this release' box.\n1. Check to make sure you've caught everything (including direct commits) using GitHub's compare tool ([example here](https://github.com/winstonjs/winston/compare/v3.6.0...master)).\n1. Update the changelog. It's nice to thank the contributors here.  It's nice to organize this by which changes would merit which level of semver bump, and especially call out any breaking changes (major-version-number) concisely at the start.\n1. **Update the version number in package.json and package-lock.json**, bumping as appropriate for [semver](https://semver.org/) based on the most significant position change trigger from the changelog you just wrote/reviewed.  Do not miss this step! Also note there are two places in package-lock where this gets updated: at the top level and under the empty-string entry of packages.\n1. Update the tag and version number on the Draft a New Release page, with the same number (which might've changed while drafting changelog notes).\n1. Make sure your local master branch is up to date.\n1. Make sure all the lint checks and tests pass, beyond what the CI might've told you.\n1. Paste the contents of the changelog for this release in the 'Describe this release' box on the Draft a Release page.\n1. Click \"Publish release.\"\n1. Back on the command line, `npm publish` and complete npm 2FA as needed.\n1. Update the distribution tags, for example: `npm dist-tag add winston@3.7.0 3.x-latest`.\n1. Verify the distribution tags look correct under the 'Versions' tab at https://www.npmjs.com/package/winston or with `npm dist-tag ls`.\n1. Keep a closer-than-usual eye on issues in the hours and days that follow, prepared to quickly revert/address anything that might be associated with that release.\n\nA more professional version of this would probably use a release branch off master to make sure no other maintainers merge a PR into master between the loading of a compare view for changelog preparation and completion of the process, but we're such a small team that the extra steps are probably not needed. After release, you can also verify with the compare view between the new and prior release tags to see when the latest change was and verify it was before you started the process.\n"
  },
  {
    "path": "docs/releases.md",
    "content": "# Past Release Roadmaps\n\nBelow is the list of items that made up the roadmap for past releases. \n\n- [Version 3.0.0](#version-300)\n\n## Legend\n\n- [ ] Unstarted work.\n- [x] Finished work.\n- [-] Partially finished or in-progress work. \n\n## Version `3.0.0`\n\n### Show stoppers\n- [x] `silent` support.\n- [x] Finish `3.0.0` upgrade guide: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md\n- [x] Triage all open issues since October 2017\n\n### High priority issues (non-blocking)\n- [x] [#1144]: this is _the_ purpose of `winston`. If we cannot log at high-volume we cannot ship out of RC. There was [test coverage for this][stress-test] that should be failing, but isnt. _(Fixed by #1291)._\n- [x] Error handling within formats [#1261]\n- [x] Update `docs/transports.md`.\n- [Type definitions for TypeScript](https://github.com/winstonjs/winston/issues/1096)\n  - [x] Supporting libraries: `winston-transport`, `logform`\n  - [x] `winston` itself \n\n### Core logging\n- [x] Make `Logger.prototype.level` and `Transport.level` play nice(r) together.\n- [x] Remove `new winston.Logger` in favor of `winston.createLogger`.\n- [x] Finish implementation for `TransportStream` and `LegacyTransportStream`. \n- [x] Move `TransportStream` and `LegacyTransportStream` into `winston-transport`.\n- [x] Move `winston/config.js` to `winston/config/index.js`\n- [x] **DEPRECATE** `winston.clone`\n- [x] Add convenience methods from `winston-transport`\n- [-] Replace all `vows`-based tests.\n  - [x] `test/*-test.js`\n  - [x] `test/formats/*-test.js` \n  - [-] `test/transports/*-test.js` \n- [x] Move `winston.config` into `triple-beam` around a base `Levels` class.\n  _(Fixed in `triple-beam@1.2.0`)_\n- [x] Update to the latest `npm` levels (e.g. including `http`).\n- [ ] Code coverage tests above 80% for `winston` _(currently `~72%`)_.\n- [x] Code coverage tests above 90% for `winston-transport`.\n- [x] Code coverage tests above 90% for `logform`\n- [-] Core scenarios covered in `abstract-winston-transport`.\n- [x] Code coverage tests above 60% for `winston-compat`.\n\n### Transports\n- [x] Implement `stream.Writable.writev` in `TransportStream`.\n- [x] Refactor all built-in transports to be TransportStream instances.\n  - [x] Console\n  - [x] File\n  - [x] Http\n  - [x] Steam\n\n### Formats\n- [x] `winston.format.colorize()` format.\n- [x] `winston.format.prettyPrint()` format.\n- [x] `winston.format.uncolorize()` format.\n- [x] `winston.format.logstash()` format.\n- [x] `winston.format.cli()`\n- [x] String interpolation _(i.e. splat)_ via format\n- [x] Use of different formats across multiple Transports. e.g.:\n   - Colors on `Console`\n   - Not on `File`\n- [x] Mutable levels on `info` objects \n   – Use `triple-beam` and `Symbol.for('level')`.\n   - Needed for `winston.formats.colorize()`. \n- [x] Quieter finalized output using `Symbol.for('message')` \n- [x] Filtering messages completely in a format.\n- [x] `winston.format.padLevels()` format.\n- [x] `humanReadableUnhandledException` should be the default\n\n### Communications / Compatibility\n- [x] Add friendly(ish) deprecation notices for common changes.\n- [x] Create `winston-compat` to help with backwards compatibility for transport authors.  \n- [x] Update the `README.md` in `winston`.\n- [x] `README.md` for `winston-transport`.\n- [x] `README.md` for `logform`.\n- [x] Migrate all `examples/*.js` to the new API.\n\n### Querying, Streaming, Uncaught Exceptions\n- [x] Uncaught Exceptions\n\n### Other Miscellaneous API changes\n- [x] Move `LogStream` back to `Logger`.\n- [x] Add LogStream.prototype.configure from `winston@2.0.0`\n- [x] `winston.Container` instances no longer add any transports by default.\n- [x] Strip wrapping `(` `)` from all occurances of `new winston.transports.*)`\n\n### Benchmarking\n- [x] Benchmark against `winston@1.0.0` in `logmark`.\n- [x] Benchmark against `winston@2.0.0` in `logmark`.\n- [x] Benchmark JSON format against `bunyan` in `logmark`.\n- [x] Benchmark against `pino` in `logmark`.\n- [x] Submit PR for all `pino` benchmarks.\n"
  },
  {
    "path": "docs/transports.md",
    "content": "# Winston Transports\n\nIn `winston` a transport is essentially a storage device for your logs. Each\ninstance of a winston logger can have multiple transports configured at\ndifferent levels. For example, one may want error logs to be stored in a\npersistent remote location (like a database), but all logs output to the\nconsole or a local file.\n\nThere are several [core transports](#built-in-to-winston) included in `winston`\nthat leverage the built-in networking and file I/O offered by Node.js core. In\naddition, there are transports which are [actively supported by winston\ncontributors](#maintained-by-winston-contributors). And last (but not least)\nthere are additional transports written by\n[members of the community](#community-transports).\n\n> Additionally there are transports previously maintained by winston\n> contributors that are [looking for maintainers](#looking-for-maintainers).\n\n* **[Built-in to winston](#built-in-to-winston)**\n  * [Console](#console-transport)\n  * [File](#file-transport)\n  * [Http](#http-transport)\n  * [Stream](#stream-transport)\n\n* **[Maintained by winston contributors](#maintained-by-winston-contributors)**\n  * [DailyRotateFile](#dailyrotatefile-transport)\n  * [MongoDB](#mongodb-transport)\n  * [Syslog](#syslog-transport)\n\n* **[Community Transports](#community-transports)**\n  * [Airbrake](#airbrake-transport)\n  * [Amazon CloudWatch](#amazon-cloudwatch-transport)\n  * [Amazon DynamoDB](#amazon-dynamodb-transport)\n  * [Amazon Kinesis Firehose](#amazon-kinesis-firehose-transport)\n  * [Amazon SNS](#amazon-sns-simple-notification-system-transport)\n  * [Azure Table](#azure-table)\n  * [Cassandra](#cassandra-transport)\n  * [Cisco Spark](#cisco-spark-transport)\n  * [Cloudant](#cloudant)\n  * [Datadog](#datadog-transport)\n  * [Elasticsearch](#elasticsearch-transport)\n  * [FastFileRotate](#fastfilerotate-transport)\n  * [Google BigQuery](#google-bigquery)\n  * [Google Stackdriver Logging](#google-stackdriver-transport)\n  * [Graylog2](#graylog2-transport)\n  * [Humio](#humio-transport)\n  * [LogDNA](#logdna-transport)\n  * [Logsene](#logsene-transport) (including Log-Alerts and Anomaly Detection)\n  * [Logz.io](#logzio-transport)\n  * [Mail](#mail-transport)\n  * [MySQL](#mysql-transport)\n  * [New Relic](#new-relic-agent-transport)\n  * [Papertrail](#papertrail-transport)\n  * [Parseable](#parseable)\n  * [PostgresQL](#postgresql-transport)\n  * [Pusher](#pusher-transport)\n  * [Sentry](#sentry-transport)\n  * [Seq](#seq-transport)\n  * [SimpleDB](#simpledb-transport)\n  * [Slack](#slack-transport)\n  * [SQLite3](#sqlite3-transport)\n  * [SSE with KOA 2](#sse-transport-with-koa-2)\n  * [Sumo Logic](#sumo-logic-transport)\n  * [VS Code extension](#vs-code-extension)\n  * [Worker Thread based async Console transport](#worker-thread-based-async-console-transport)\n  * [Winlog2 Transport](#winlog2-transport)\n\n* **[Looking for maintainers](#looking-for-maintainers)**\n  * [CouchDB](#couchdb-transport)\n  * [Loggly](#loggly-transport)\n  * [Redis](#redis-transport)\n  * [Riak](#riak-transport)\n\n## Built-in to winston\n\nThere are several core transports included in `winston`, which leverage the built-in networking and file I/O offered by Node.js core.\n\n* [Console](#console-transport)\n* [File](#file-transport)\n* [Http](#http-transport)\n* [Stream](#stream-transport)\n\n### Console Transport\n\n``` js\nlogger.add(new winston.transports.Console(options));\n```\n\nThe Console transport takes a few simple options:\n\n* __level:__ Level of messages that this transport should log (default: level set on parent logger).\n* __silent:__ Boolean flag indicating whether to suppress output (default false).\n* __eol:__ string indicating the end-of-line characters to use (default `os.EOL`)\n* __stderrLevels__ Array of strings containing the levels to log to stderr instead of stdout, for example `['error', 'debug', 'info']`. (default `[]`)\n* __consoleWarnLevels__ Array of strings containing the levels to log using console.warn or to stderr (in Node.js) instead of stdout, for example `['warn', 'debug']`. (default `[]`)\n\n### File Transport\n``` js\nlogger.add(new winston.transports.File(options));\n```\n\nThe File transport supports a variety of file writing options. If you are\nlooking for daily log rotation see [DailyRotateFile](#dailyrotatefile-transport)\n\n* __level:__ Level of messages that this transport should log (default: level set on parent logger).\n* __silent:__ Boolean flag indicating whether to suppress output (default false).\n* __eol:__ Line-ending character to use. (default: `os.EOL`).\n* __lazy:__ If true, log files will be created on demand, not at the initialization time.\n* __filename:__ The filename of the logfile to write output to.\n* __maxsize:__ Max size in bytes of the logfile, if the size is exceeded then a new file is created, a counter will become a suffix of the log file.\n* __maxFiles:__ Limit the number of files created when the size of the logfile is exceeded.\n* __tailable:__ If true, log files will be rolled based on maxsize and maxfiles, but in ascending order. The __filename__ will always have the most recent log lines. The larger the appended number, the older the log file.  This option requires __maxFiles__ to be set, or it will be ignored.\n* __maxRetries:__ The number of stream creation retry attempts before entering a failed state. In a failed state the transport stays active but performs a NOOP on it's log function. (default 2)\n* __zippedArchive:__ If true, all log files but the current one will be zipped.\n* __options:__ options passed to `fs.createWriteStream` (default `{flags: 'a'}`).\n* __stream:__ **DEPRECATED** The WriteableStream to write output to.\n\n### Http Transport\n\n``` js\nlogger.add(new winston.transports.Http(options));\n```\n\nThe `Http` transport is a generic way to log, query, and stream logs from an arbitrary Http endpoint, preferably [winstond][1]. It takes options that are passed to the node.js `http` or `https` request:\n\n* __host:__ (Default: **localhost**) Remote host of the HTTP logging endpoint\n* __port:__ (Default: **80 or 443**) Remote port of the HTTP logging endpoint\n* __path:__ (Default: **/**) Remote URI of the HTTP logging endpoint\n* __auth:__ (Default: **None**) An object representing the `username` and `password` for HTTP Basic Auth\n* __ssl:__ (Default: **false**) Value indicating if we should use HTTPS\n* __batch:__ (Default: **false**) Value indicating if batch mode should be used. A batch of logs to send through the HTTP request when one of the batch options is reached: number of elements, or timeout\n* __batchInterval:__ (Default: **5000 ms**) Value indicating the number of milliseconds to wait before sending the HTTP request\n* __batchCount:__ (Default: **10**) Value indicating the number of logs to cumulate before sending the HTTP request\n\n### Stream Transport\n\n``` js\nlogger.add(new winston.transports.Stream({\n  stream: fs.createWriteStream('/dev/null')\n  /* other options */\n}));\n```\n\nThe Stream transport takes a few simple options:\n\n* __stream:__ any Node.js stream. If an `objectMode` stream is provided then\n  the entire `info` object will be written. Otherwise `info[MESSAGE]` will be\n  written.\n* __level:__ Level of messages that this transport should log (default: level set on parent logger).\n* __silent:__ Boolean flag indicating whether to suppress output (default false).\n* __eol:__ Line-ending character to use. (default: `os.EOL`).\n\n## Maintained by winston contributors\n\nStarting with `winston@0.3.0` an effort was made to remove any transport which added additional dependencies to `winston`. At the time there were several transports already in `winston` which will have slowly waned in usage. The\nfollowing transports are **actively maintained by members of the winston Github\norganization.**\n\n* [MongoDB](#mongodb-transport)\n* [DailyRotateFile](#dailyrotatefile-transport)\n* [Syslog](#syslog-transport)\n\n### MongoDB Transport\n\nAs of `winston@0.3.0` the MongoDB transport has been broken out into a new module: [winston-mongodb][14]. Using it is just as easy:\n\n``` js\nconst winston = require('winston');\n\n/**\n * Requiring `winston-mongodb` will expose\n * `winston.transports.MongoDB`\n */\nrequire('winston-mongodb');\n\nlogger.add(new winston.transports.MongoDB(options));\n```\n\nThe MongoDB transport takes the following options. 'db' is required:\n\n* __level:__ Level of messages that this transport should log, defaults to\n'info'.\n* __silent:__ Boolean flag indicating whether to suppress output, defaults to\nfalse.\n* __db:__ MongoDB connection uri, pre-connected db object or promise object\nwhich will be resolved with pre-connected db object.\n* __options:__ MongoDB connection parameters (optional, defaults to\n`{poolSize: 2, autoReconnect: true}`).\n* __collection__: The name of the collection you want to store log messages in,\ndefaults to 'log'.\n* __storeHost:__ Boolean indicating if you want to store machine hostname in\nlogs entry, if set to true it populates MongoDB entry with 'hostname' field,\nwhich stores os.hostname() value.\n* __username:__ The username to use when logging into MongoDB.\n* __password:__ The password to use when logging into MongoDB. If you don't\nsupply a username and password it will not use MongoDB authentication.\n* __label:__ Label stored with entry object if defined.\n* __name:__ Transport instance identifier. Useful if you need to create multiple\nMongoDB transports.\n* __capped:__ In case this property is true, winston-mongodb will try to create\nnew log collection as capped, defaults to false.\n* __cappedSize:__ Size of logs capped collection in bytes, defaults to 10000000.\n* __cappedMax:__ Size of logs capped collection in number of documents.\n* __tryReconnect:__ Will try to reconnect to the database in case of fail during\ninitialization. Works only if __db__ is a string. Defaults to false.\n* __expireAfterSeconds:__ Seconds before the entry is removed. Works only if __capped__ is not set.\n\n*Metadata:* Logged as a native JSON object in 'meta' property.\n\n*Logging unhandled exceptions:* For logging unhandled exceptions specify\nwinston-mongodb as `handleExceptions` logger according to winston documentation.\n\n### DailyRotateFile Transport\n\nSee [winston-dailyrotatefile](https://github.com/winstonjs/winston-daily-rotate-file).\n\n### Syslog Transport\n\nSee [winston-syslog](https://github.com/winstonjs/winston-syslog).\n\n## Community Transports\n\nThe community has truly embraced `winston`; there are over **23** winston transports and over half of them are maintained by authors external to the winston core team. If you want to check them all out, just search `npm`:\n\n``` bash\n  $ npm search winston\n```\n\n**If you have an issue using one of these modules you should contact the module author directly**\n\n### Airbrake Transport\n\n[winston-airbrake2][22] is a transport for winston that sends your logs to Airbrake.io.\n\n``` js\nconst winston = require('winston');\nconst { Airbrake } = require('winston-airbrake2');\nlogger.add(new Airbrake(options));\n```\n\nThe Airbrake transport utilises the node-airbrake module to send logs to the Airbrake.io API. You can set the following options:\n\n* __apiKey__: The project API Key. (required, default: null)\n* __name__: Transport name. (optional, default: 'airbrake')\n* __level__: The level of message that will be sent to Airbrake (optional, default: 'error')\n* __host__: The information that is displayed within the URL of the Airbrake interface. (optional, default: 'http://' + os.hostname())\n* __env__: The environment will dictate what happens with your message. If your environment is currently one of the 'developmentEnvironments', the error will not be sent to Airbrake. (optional, default: process.env.NODE_ENV)\n* __timeout__: The maximum time allowed to send to Airbrake in milliseconds. (optional, default: 30000)\n* __developmentEnvironments__: The environments that will **not** send errors to Airbrake. (optional, default: ['development', 'test'])\n* __projectRoot__: Extra string sent to Airbrake. (optional, default: null)\n* __appVersion__: Extra string or number sent to Airbrake. (optional, default: null)\n* __consoleLogError__: Toggle the logging of errors to console when the current environment is in the developmentEnvironments array. (optional, default: false)\n\n### Amazon CloudWatch Transport\n\nThe [winston-aws-cloudwatch][25] transport relays your log messages to Amazon CloudWatch.\n\n```js\nconst winston = require('winston');\nconst AwsCloudWatch = require('winston-aws-cloudwatch');\n\nlogger.add(new AwsCloudWatch(options));\n```\n\nOptions:\n\n* __logGroupName:__ The name of the CloudWatch log group to which to log. *[required]*\n* __logStreamName:__ The name of the CloudWatch log stream to which to log. *[required]*\n* __awsConfig:__ An object containing your `accessKeyId`, `secretAccessKey`, `region`, etc.\n\n~~Alternatively, you may be interested in [winston-cloudwatch][26].~~\n`lazywithclass/winston-cloudwatch` is no longer maintained. Use\n[@initd-sg/winston-cloudwatch](https://github.com/initdsg/winston-cloudwatch)\n\n### Amazon DynamoDB Transport\nThe [winston-dynamodb][36] transport uses Amazon's DynamoDB as a sink for log messages. You can take advantage of the various authentication methods supports by Amazon's aws-sdk module. See [Configuring the SDK in Node.js](http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html).\n\n``` js\nconst winston = require('winston');\nconst { DynamoDB } = require('winston-dynamodb');\n\nlogger.add(new DynamoDB(options));\n```\n\nOptions:\n* __accessKeyId:__ your AWS access key id\n* __secretAccessKey:__ your AWS secret access key\n* __region:__ the region where the domain is hosted\n* __useEnvironment:__ use process.env values for AWS access, secret, & region.\n* __tableName:__ DynamoDB table name\n\nTo Configure using environment authentication:\n``` js\nlogger.add(new winston.transports.DynamoDB({\n  useEnvironment: true,\n  tableName: 'log'\n}));\n```\n\nAlso supports callbacks for completion when the DynamoDB putItem has been completed.\n\n### Amazon Kinesis Firehose Transport\n\nThe [winston-firehose][28] transport relays your log messages to Amazon Kinesis Firehose.\n\n```js\nconst winston = require('winston');\nconst WFirehose = require('winston-firehose');\n\nlogger.add(new WFirehose(options));\n```\n\nOptions:\n\n* __streamName:__ The name of the Amazon Kinesis Firehose stream to which to log. *[required]*\n* __firehoseOptions:__ The AWS Kinesis firehose options to pass direction to the firehose client, [as documented by AWS](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Firehose.html#constructor-property). *[required]*\n\n### Amazon SNS (Simple Notification System) Transport\n\nThe [winston-sns][18] transport uses amazon SNS to send emails, texts, or a bunch of other notifications. Since this transport uses the Amazon AWS SDK for JavaScript, you can take advantage of the various methods of authentication found in Amazon's [Configuring the SDK in Node.js](http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html) document.\n\n``` js\nconst winston = require('winston');\nconst SnsTransport = require('winston-sns');\n\nlogger.add(new SnsTransport(options));\n```\n\nOptions:\n\n* __subscriber:__ Subscriber number - found in your SNS AWS Console, after clicking on a topic. Same as AWS Account ID. *[required]*\n* __topic_arn:__ Also found in SNS AWS Console - listed under a topic as Topic ARN. *[required]*\n* __aws_key:__ Your Amazon Web Services Key.\n* __aws_secret:__ Your Amazon Web Services Secret.\n* __region:__ AWS Region to use. Can be one of: `us-east-1`,`us-west-1`,`eu-west-1`,`ap-southeast-1`,`ap-northeast-1`,`us-gov-west-1`,`sa-east-1`. (default: `us-east-1`)\n* __subject:__ Subject for notifications. Uses placeholders for level (%l), error message (%e), and metadata (%m). (default: \"Winston Error Report\")\n* __message:__ Message of notifications. Uses placeholders for level (%l), error message (%e), and metadata (%m). (default: \"Level '%l' Error:\\n%e\\n\\nMetadata:\\n%m\")\n* __level:__ lowest level this transport will log. (default: `info`)\n* __json:__ use json instead of a prettier (human friendly) string for meta information in the notification. (default: `false`)\n* __handleExceptions:__ set to true to have this transport handle exceptions. (default: `false`)\n\n### Azure Table\n\n[winston-azuretable][21] is a Azure Table transport:\n\n``` js\nconst { AzureLogger } = require('winston-azuretable');\nlogger.add(new AzureLogger(options));\n```\n\nThe Azure Table transport connects to an Azure Storage Account using the following options:\n\n* __useDevStorage__: Boolean flag denoting whether to use the Azure Storage Emulator (default: `false`)\n* __account__: Azure Storage Account Name. In lieu of this setting, you can set the environment variable: `AZURE_STORAGE_ACCOUNT`\n* __key__: Azure Storage Account Key. In lieu of this setting, you can set the environment variable: `AZURE_STORAGE_ACCESS_KEY`\n* __level__: lowest logging level transport to be logged (default: `info`)\n* __tableName__: name of the table to log messages (default: `log`)\n* __partitionKey__: table partition key to use (default: `process.env.NODE_ENV`)\n* __silent__: Boolean flag indicating whether to suppress output (default: `false`)\n\n### Cassandra Transport\n\n[winston-cassandra][20] is a Cassandra transport:\n\n``` js\nconst Cassandra = require('winston-cassandra').Cassandra;\nlogger.add(new Cassandra(options));\n```\n\nThe Cassandra transport connects to a cluster using the native protocol with the following options:\n\n* __level:__ Level of messages that this transport should log (default: `'info'`).\n* __table:__ The name of the Cassandra column family you want to store log messages in (default: `'logs'`).\n* __partitionBy:__ How you want the logs to be partitioned. Possible values `'hour'` and `'day'`(Default).\n* __consistency:__ The consistency of the insert query (default: `quorum`).\n\nIn addition to the options accepted by the [Node.js Cassandra driver](https://github.com/jorgebay/node-cassandra-cql) Client.\n\n* __hosts:__ Cluster nodes that will handle the write requests:\nArray of strings containing the hosts, for example `['host1', 'host2']` (required).\n* __keyspace:__ The name of the keyspace that will contain the logs table (required). The keyspace should be already created in the cluster.\n\n### Cisco Spark Transport\n\n[winston-spark][31] is a transport for [Cisco Spark](https://www.ciscospark.com/)\n\n``` js\nconst winston = require('winston');\nrequire('winston-spark');\n\nconst options = {\n  accessToken: '***Your Spark Access Token***',\n  roomId: '***Spark Room Id***'\n};\n\nlogger.add(new winston.transports.SparkLogger(options));\n```\n\nValid Options are as the following:\n* __accessToken__ Your Spark Access Token. *[required]*\n* __roomId__ Spark Room Id. *[required]*\n* __level__ Log Level (default: info)\n* __hideMeta__ Hide MetaData (default: false)\n\n### Cloudant\n[winston-clodant][34] is a transport for Cloudant NoSQL Db.\n\n```js\nconst winston = require('winston');\nconst WinstonCloudant = require('winston-cloudant');\nlogger.add(new WinstonCloudant(options));\n```\n\nThe Cloudant transport takes the following options:\n\n    url         : Access url including user and password [required]\n    username    : Username for the Cloudant DB instance\n    password    : Password for the Cloudant DB instance\n    host        : Host for the Cloudant DB instance\n    db          : Name of the databasename to put logs in\n    logstash    : Write logs in logstash format\n\n### Datadog Transport\n[datadog-logger-integrations][38] is a transport to ship your logs to DataDog.\n\n```javascript\nvar winston = require('winston')\nvar { DataDogTransport } = require('datadog-logger-integrations/winston')\n\nvar logger = winston.createLogger({\n  // Whatever options you need\n  // Refer https://github.com/winstonjs/winston#creating-your-own-logger\n})\n\nlogger.add(\n  new DataDogTransport({\n    ddClientConfig: {\n      authMethods: {\n        apiKeyAuth: apiKey,\n      },\n    },\n    service: 'super_service',\n    ddSource: 'nodejs',\n    ddTags: 'foo:bar,boo:baz'\n  })\n)\n```\n\nOptions:\n* __ddClientConfig__: DataDog client config *[required]*\n* __service__: The name of the application or service generating the logs\n* __ddsource__: The technology from which the logs originated\n* __ddtags__: Metadata associated with the logs\n\n### Google BigQuery\n[winston-bigquery][42] is a transport for Google BigQuery.\n\n```js\nimport {WinstonBigQuery} from 'winston-bigquery';\nimport winston, {format} from 'winston';\n\nconst logger = winston.createLogger({\n\ttransports: [\n\t\tnew WinstonBigQuery({\n\t\t\ttableId: 'winston_logs',\n\t\t\tdatasetId: 'logs'\n\t\t})\n\t]\n});\n```\n\nThe Google BigQuery takes the following options:\n\n* __datasetId__   \t      \t    : Your dataset name [required]\n* __tableId__     \t  \t    : Table name in the datase [required]\n* __applicationCredentials__    : a path to local service worker (useful in dev env) [Optional]\n\n**Pay Attention**, since BQ, unlike some other products, is not a \"schema-less\" you will need to build the schema in advance.\nread more on the topic on [github][42] or [npmjs.com][43]\n\n### Google Stackdriver Transport\n\n[@google-cloud/logging-winston][29] provides a transport to relay your log messages to [Stackdriver Logging][30].\n\n```js\nconst winston = require('winston');\nconst Stackdriver = require('@google-cloud/logging-winston');\nlogger.add(new Stackdriver({\n  projectId: 'your-project-id',\n  keyFilename: '/path/to/keyfile.json'\n}));\n```\n\n### Graylog2 Transport\n\n[winston-graylog2][19] is a Graylog2 transport:\n\n``` js\nconst winston = require('winston');\nconst Graylog2 = require('winston-graylog2');\nlogger.add(new Graylog2(options));\n```\n\nThe Graylog2 transport connects to a Graylog2 server over UDP using the following options:\n\n* __name__:  Transport name\n* __level__: Level of messages this transport should log. (default: info)\n* __silent__: Boolean flag indicating whether to suppress output. (default: false)\n* __handleExceptions__: Boolean flag, whenever to handle uncaught exceptions. (default: false)\n* __graylog__:\n  - __servers__; list of graylog2 servers\n    * __host__: your server address (default: localhost)\n    * __port__: your server port (default: 12201)\n  - __hostname__: the name of this host (default: os.hostname())\n  - __facility__: the facility for these log messages (default: \"Node.js\")\n  - __bufferSize__: max UDP packet size, should never exceed the MTU of your system (default: 1400)\n\n### Elasticsearch Transport\n\nLog to Elasticsearch in a logstash-like format and\nleverage Kibana to browse your logs.\n\nSee: https://github.com/vanthome/winston-elasticsearch.\n\n### FastFileRotate Transport\n\n[fast-file-rotate][35] is a performant file transport providing daily log rotation.\n\n```js\nconst FileRotateTransport = require('fast-file-rotate');\nconst winston = require('winston');\n\nconst logger = winston.createLogger({\n  transports: [\n    new FileRotateTransport({\n      fileName: __dirname + '/console%DATE%.log'\n    })\n  ]\n})\n```\n\n### Humio Transport\n\n[humio-winston][44] is a transport for sending logs to Humio:\n\n``` js\nconst winston = require('winston');\nconst HumioTransport = require('humio-winston');\n\nconst logger = winston.createLogger({\n  transports: [\n    new HumioTransport({\n      ingestToken: '<YOUR HUMIO INGEST TOKEN>',\n    }),\n  ],\n});\n```\n\n### LogDNA Transport\n\n[LogDNA Winston][37] is a transport for being able to forward the logs to [LogDNA](https://logdna.com/):\n\n``` js\nconst logdnaWinston = require('logdna-winston');\nconst winston = require('winston');\nconst logger = winston.createLogger({});\nconst options = {\n    key: apikey, // the only field required\n    hostname: myHostname,\n    ip: ipAddress,\n    mac: macAddress,\n    app: appName,\n    env: envName,\n    index_meta: true // Defaults to false, when true ensures meta object will be searchable\n};\n\n// Only add this line in order to track exceptions\noptions.handleExceptions = true;\n\nlogger.add(new logdnaWinston(options));\n\nlet meta = {\n    data:'Some information'\n};\nlogger.log('info', 'Log from LogDNA Winston', meta);\n```\n\n### Logzio Transport\n\nYou can download the logzio transport here : [https://github.com/logzio/winston-logzio](https://github.com/logzio/winston-logzio)\n\n*Basic Usage*\n```js\nconst winston = require('winston');\nconst Logzio = require('winston-logzio');\n\nlogger.add(new Logzio({\n  token: '__YOUR_API_TOKEN__'\n}));\n```\n\nFor more information about how to configure the logzio transport, view the README.md in the [winston-logzio repo](https://github.com/logzio/winston-logzio).\n\n### Logsene Transport\n\n[winston-logsene][24] transport for Elasticsearch bulk indexing via HTTPS to Logsene:\n\n``` js\nconst winston = require('winston');\nconst Logsene = require('winston-logsene');\n\nlogger.add(new Logsene({\n  token: process.env.LOGSENE_TOKEN\n  /* other options */\n}));\n```\nOptions:\n* __token__: Logsene Application Token\n* __source__: Source of the logs (defaults to main module)\n\n[Logsene](http://www.sematext.com/logsene/) features:\n- Fulltext search\n- Anomaly detection and alerts\n- Kibana4 integration\n- Integration with [SPM Performance Monitoring for Node.js](http://www.sematext.com/spm/integrations/nodejs-monitoring.html)\n\n### Mail Transport\n\nThe [winston-mail][16] is an email transport:\n\n``` js\nconst { Mail } = require('winston-mail');\nlogger.add(new Mail(options));\n```\n\nThe Mail transport uses [node-mail][17] behind the scenes.  Options are the following, `to` and `host` are required:\n\n* __to:__ The address(es) you want to send to. *[required]*\n* __from:__ The address you want to send from. (default: `winston@[server-host-name]`)\n* __host:__ SMTP server hostname\n* __port:__ SMTP port (default: 587 or 25)\n* __secure:__ Use secure\n* __username__ User for server auth\n* __password__ Password for server auth\n* __level:__ Level of messages that this transport should log.\n* __silent:__ Boolean flag indicating whether to suppress output.\n\n*Metadata:* Stringified as JSON in email.\n\n### MySQL Transport\n\n[winston-mysql](https://github.com/charles-zh/winston-mysql) is a MySQL transport for Winston.\n\nCreate a table in your database first:\n\n```sql\n CREATE TABLE `sys_logs_default` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `level` VARCHAR(16) NOT NULL,\n `message` VARCHAR(2048) NOT NULL,\n `meta` VARCHAR(2048) NOT NULL,\n `timestamp` DATETIME NOT NULL,\n PRIMARY KEY (`id`));\n```\n\n> You can also specify `meta` to be a `JSON` field on MySQL 5.7+, i.e., ``meta` JSON NOT NULL`, which is helfpul for searching and parsing.\n\nConfigure Winston with the transport:\n\n```javascript\nimport MySQLTransport from 'winston-mysql';\n\nconst options = {\n    host: '${MYSQL_HOST}',\n    user: '${MYSQL_USER}',\n    password: '${MYSQL_PASSWORD}',\n    database: '${MYSQL_DATABASE}',\n    table: 'sys_logs_default'\n};\n\nconst logger = winston.createLogger({\n    level: 'debug',\n    format: winston.format.json(),\n    defaultMeta: { service: 'user-service' },\n    transports: [\n        new winston.transports.Console({\n            format: winston.format.simple(),\n        }),\n        new MySQLTransport(options),\n    ],\n});\n\n/// ...\nlet msg = 'My Log';\nlogger.info(msg, {message: msg, type: 'demo'});\n```\n\n\n### New Relic Agent Transport\n\n[winston-newrelic-agent-transport][47] is a New Relic transport that leverages the New Relic agent:\n\n``` js\nimport winston from 'winston'\nimport NewrelicTransport from 'winston-newrelic-agent-transport'\n\nconst logger = winston.createLogger()\n\nconst options = {}\nlogger.add(new NewrelicTransport(options))\n```\n\nThe New Relic agent typically automatically forwards Winston logs to New Relic when using CommonJS. With CommonJS no additional transport should be needed. However, when using ECMAScript modules, the automatic forwarding of logs can with certain coding patterns not work. If the New Relic agent is not automatically forwarding your logs, this transport provides a solution.\n\nOptions:\n\n* __level__ (optional): The Winston logging level to use as the maximum level of messages that the transport will log.\n* __rejectCriteria__ (optional): The rejectCriteria option allows you to specify an array of regexes that will be matched against either the Winston info object or log message to determine whether or not a log message should be rejected and not logged to New Relic.\n\n### Papertrail Transport\n\n[winston-papertrail][27] is a Papertrail transport:\n\n``` js\nconst { Papertrail } = require('winston-papertrail');\nlogger.add(new Papertrail(options));\n```\n\nThe Papertrail transport connects to a [PapertrailApp log destination](https://papertrailapp.com) over TCP (TLS) using the following options:\n\n* __level:__ Level of messages this transport should log. (default: info)\n* __host:__ FQDN or IP address of the Papertrail endpoint.\n* __port:__ Port for the Papertrail log destination.\n* __hostname:__ The hostname associated with messages. (default: require('os').hostname())\n* __program:__ The facility to send log messages.. (default: default)\n* __logFormat:__ a log formatting function with the signature `function(level, message)`, which allows custom formatting of the level or message prior to delivery\n\n*Metadata:* Logged as a native JSON object to the 'meta' attribute of the item.\n\n### Parseable Transport\n\n[Parseable](https://parseable.com/) is an open source, general purpose log analytics system. [Parseable-Winston](https://github.com/jybleau/parseable-node-loggers/tree/main/packages/winston#parseable-winston) is a Parseable transport for Winston.\n\n```js\n// Using cjs\nconst { ParseableTransport } = require('parseable-winston')\nconst winston = require('winston')\n\nconst parseable = new ParseableTransport({\n  url: process.env.PARSEABLE_LOGS_URL, // Ex: 'https://parsable.myserver.local/api/v1/logstream'\n  username: process.env.PARSEABLE_LOGS_USERNAME,\n  password: process.env.PARSEABLE_LOGS_PASSWORD,\n  logstream: process.env.PARSEABLE_LOGS_LOGSTREAM, // The logstream name\n  tags: { tag1: 'tagValue' } // optional tags to be added with each ingestion\n})\n\nconst logger = winston.createLogger({\n  levels: winston.config.syslog.levels,\n  transports: [parseable],\n  defaultMeta: { instance: 'app', hostname: 'app1' }\n})\n\nlogger.info('User took the goggles', { userid: 1, user: { name: 'Rainier Wolfcastle' } })\nlogger.warning('The goggles do nothing', { userid: 1 })\n```\n\n### PostgresQL Transport\n\n[@pauleliet/winston-pg-native](https://github.com/petpano/winston-pg-native) is a PostgresQL transport supporting Winston 3.X.\n\n### Pusher Transport\n[winston-pusher](https://github.com/meletisf/winston-pusher) is a Pusher transport.\n\n```js\nconst { PusherLogger } = require('winston-pusher');\nlogger.add(new PusherLogger(options));\n```\n\nThis transport sends the logs to a Pusher app for real time processing and it uses the following options:\n\n* __pusher__ [Object]\n  * __appId__ The application id obtained from the dashboard\n  * __key__ The application key obtained from the dashboard\n  * __secret__ The application secret obtained from the dashboard\n  * __cluster__ The cluster\n  * __encrypted__ Whether the data will be send through SSL\n* __channel__ The channel of the event (default: default)\n* __event__ The event name (default: default)\n\n### Sentry Transport\n[winston-transport-sentry-node][41] is a transport for [Sentry](https://sentry.io/) uses [@sentry/node](https://www.npmjs.com/package/@sentry/node).\n\n```js\nconst Sentry = require('winston-transport-sentry-node').default;\nlogger.add(new Sentry({\n  sentry: {\n    dsn: 'https://******@sentry.io/12345',\n  },\n  level: 'info'\n}));\n```\n\nThis transport takes the following options:\n\n* __sentry:__ [Object]\n  * __dsn:__ Sentry DSN or Data Source Name (default: `process.env.SENTRY_DSN`) **REQUIRED**\n  * __environment:__ The application environment (default: `process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV || 'production'`)\n  * __serverName:__  The application name\n  * __debug:__ Turns debug mode on or off (default: `process.env.SENTRY_DEBUG || false`)\n  * __sampleRate:__ Sample rate as a percentage of events to be sent in the range of 0.0 to 1.0 (default: `1.0`)\n  * __maxBreadcrumbs:__ Total amount of breadcrumbs that should be captured (default: `100`)\n* __level:__ Level of messages that this transport should log\n* __silent:__  Boolean flag indicating whether to suppress output, defaults to false\n\n### Seq Transport\n\n[winston-seq][45] is a transport that sends structured log events to [Seq](https://datalust.co/seq).\n\n```js\nconst { SeqTransport } = require('@datalust/winston-seq');\nlogger.add(new SeqTransport({\n  serverUrl: \"https://your-seq-server:5341\",\n  apiKey: \"your-api-key\",\n  onError: (e => { console.error(e) }),\n}));\n```\n\n`SeqTransport` is configured with the following options:\n\n* __serverUrl__ - the URL for your Seq server's ingestion\n* __apiKey__ - (optional) The Seq API Key to use\n* __onError__ - Callback to execute when an error occurs within the transport\n\n### SimpleDB Transport\n\nThe [winston-simpledb][15] transport is just as easy:\n\n``` js\nconst SimpleDB = require('winston-simpledb').SimpleDB;\nlogger.add(new SimpleDB(options));\n```\n\nThe SimpleDB transport takes the following options. All items marked with an asterisk are required:\n\n* __awsAccessKey__:* your AWS Access Key\n* __secretAccessKey__:* your AWS Secret Access Key\n* __awsAccountId__:* your AWS Account Id\n* __domainName__:* a string or function that returns the domain name to log to\n* __region__:* the region your domain resides in\n* __itemName__: a string ('uuid', 'epoch', 'timestamp') or function that returns the item name to log\n\n*Metadata:* Logged as a native JSON object to the 'meta' attribute of the item.\n\n### Slack Transport\n[winston-slack-webhook-transport][39] is a transport that sends all log messages to the Slack chat service.\n\n```js\nconst winston = require('winston');\nconst SlackHook = require('winston-slack-webhook-transport');\n\nconst logger = winston.createLogger({\n\tlevel: 'info',\n\ttransports: [\n\t\tnew SlackHook({\n\t\t\twebhookUrl: 'https://hooks.slack.com/services/xxx/xxx/xxx'\n\t\t})\n\t]\n});\n\nlogger.info('This should now appear on Slack');\n```\n\nThis transport takes the following options:\n\n* __webhookUrl__ - Slack incoming webhook URL. This can be from a basic integration or a bot. **REQUIRED**\n* __channel__ - Slack channel to post message to.\n* __username__ - Username to post message with.\n* __iconEmoji__ - Status icon to post message with. (interchangeable with __iconUrl__)\n* __iconUrl__ - Status icon to post message with. (interchangeable with __iconEmoji__)\n* __formatter__ - Custom function to format messages with. This function accepts the __info__ object ([see Winston documentation](https://github.com/winstonjs/winston/blob/master/README.md#streams-objectmode-and-info-objects)) and must return an object with at least one of the following three keys: __text__ (string), __attachments__ (array of [attachment objects](https://api.slack.com/docs/message-attachments)), __blocks__ (array of [layout block objects](https://api.slack.com/messaging/composing/layouts)). These will be used to structure the format of the logged Slack message. By default, messages will use the format of `[level]: [message]` with no attachments or layout blocks.\n* __level__ - Level to log. Global settings will apply if this is blank.\n* __unfurlLinks__ - Enables or disables [link unfurling.](https://api.slack.com/docs/message-attachments#unfurling) (Default: false)\n* __unfurlMedia__ - Enables or disables [media unfurling.](https://api.slack.com/docs/message-link-unfurling) (Default: false)\n* __mrkdwn__ - Enables or disables [`mrkdwn` formatting](https://api.slack.com/messaging/composing/formatting#basics) within attachments or layout blocks (Default: false)\n\n### SQLite3 Transport\n\nThe [winston-better-sqlite3][40] transport uses [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3).\n\n```js\nconst wbs = require('winston-better-sqlite3');\nlogger.add(new wbs({\n\n    // path to the sqlite3 database file on the disk\n    db: '<name of sqlite3 database file>',\n\n    // A list of params to log\n    params: ['level', 'message']\n}));\n```\n\n### Sumo Logic Transport\n[winston-sumologic-transport][32] is a transport for Sumo Logic\n\n``` js\nconst winston = require('winston');\nconst { SumoLogic } = require('winston-sumologic-transport');\n\nlogger.add(new SumoLogic(options));\n```\n\nOptions:\n* __url__: The Sumo Logic HTTP collector URL\n\n### SSE transport with KOA 2\n[winston-koa-sse](https://github.com/alexvictoor/winston-koa-sse) is a transport that leverages on Server Sent Event. With this transport you can use your browser console to view your server logs.\n\n### VS Code extension\n\n[winston-transport-vscode][48] is a transport for VS Code extension development.\n\n```js\nconst vscode = require('vscode');\nconst winston = require('winston');\nconst { OutputChannelTransport } = require('winston-transport-vscode');\n\nconst outputChannel = vscode.window.createOutputChannel('My extension');\n\nconst logger = winston.createLogger({\n  transports: [new OutputChannelTransport({ outputChannel })],\n});\n```\n\nThe extension includes dedicated log levels and format for using with VS Code's\nLogOutputChannel.\n\n```js\nconst { LogOutputChannelTransport } = require('winston-transport-vscode');\n\nconst outputChannel = vscode.window.createOutputChannel('My extension', {\n  log: true,\n});\n\nconst logger = winston.createLogger({\n  levels: LogOutputChannelTransport.config.levels,\n  format: LogOutputChannelTransport.format(),\n  transports: [new LogOutputChannelTransport({ outputChannel })],\n});\n```\n\n\n### Worker Thread based async Console transport\n\n[winston-console-transport-in-worker][46]\n\n```typescript\nimport * as winston from 'winston';\nimport { ConsoleTransportInWorker } from '@greeneyesai/winston-console-transport-in-worker';\n\n...\n\nexport const logger: winston.Logger = winston.createLogger({\n    format: combine(timestamp(), myFormat),\n    level: Level.INFO,\n    transports: [new ConsoleTransportInWorker()],\n});\n```\n\nThe `ConsoleTransportInWorker` is a subclass of `winston.transports.Console` therefore accepting the same options as the `Console` transport.\n\nTypeScript supported.\n\n### Winlog2 Transport\n\n[winston-winlog2][33] is a Windows Event log transport:\n\n``` js\nconst winston = require('winston');\nconst Winlog2 = require('winston-winlog2');\nlogger.add(new Winlog2(options));\n```\n\nThe winlog2 transport uses the following options:\n\n* __name__:  Transport name\n* __eventLog__: Log type (default: 'APPLICATION')\n* __source__: Name of application which will appear in event log (default: 'node')\n\n## Looking for maintainers\n\nThese transports are part of the `winston` Github organization but are\nactively seeking new maintainers. Interested in getting involved? Open an\nissue on `winston` to get the conversation started!\n\n* [CouchDB](#couchdb-transport)\n* [Loggly](#loggly-transport)\n* [Redis](#redis-transport)\n* [Riak](#riak-transport)\n\n### CouchDB Transport\n\n_As of `winston@0.6.0` the CouchDB transport has been broken out into a new module: [winston-couchdb][2]._\n\n``` js\nconst WinstonCouchDb = require('winston-couchdb');\nlogger.add(new WinstonCouchdb(options));\n```\n\nThe `Couchdb` will place your logs in a remote CouchDB database. It will also create a [Design Document][3], `_design/Logs` for later querying and streaming your logs from CouchDB. The transport takes the following options:\n\n* __host:__ (Default: **localhost**) Remote host of the HTTP logging endpoint\n* __port:__ (Default: **5984**) Remote port of the HTTP logging endpoint\n* __db:__ (Default: **winston**) Remote URI of the HTTP logging endpoint\n* __auth:__ (Default: **None**) An object representing the `username` and `password` for HTTP Basic Auth\n* __ssl:__ (Default: **false**) Value indicating if we should us HTTPS\n\n### Loggly Transport\n\n_As of `winston@0.6.0` the Loggly transport has been broken out into a new module: [winston-loggly][5]._\n\n``` js\nconst WinstonLoggly = require('winston-loggly');\nlogger.add(new winston.transports.Loggly(options));\n```\n\nThe Loggly transport is based on [Nodejitsu's][6] [node-loggly][7] implementation of the [Loggly][8] API. If you haven't heard of Loggly before, you should probably read their [value proposition][9]. The Loggly transport takes the following options. Either 'inputToken' or 'inputName' is required:\n\n* __level:__ Level of messages that this transport should log.\n* __subdomain:__ The subdomain of your Loggly account. *[required]*\n* __auth__: The authentication information for your Loggly account. *[required with inputName]*\n* __inputName:__ The name of the input this instance should log to.\n* __inputToken:__ The input token of the input this instance should log to.\n* __json:__ If true, messages will be sent to Loggly as JSON.\n\n### Redis Transport\n\n``` js\nconst WinstonRedis = require('winston-redis');\nlogger.add(new WinstonRedis(options));\n```\n\nThis transport accepts the options accepted by the [node-redis][4] client:\n\n* __host:__ (Default **localhost**) Remote host of the Redis server\n* __port:__ (Default **6379**) Port the Redis server is running on.\n* __auth:__ (Default **None**) Password set on the Redis server\n\nIn addition to these, the Redis transport also accepts the following options.\n\n* __length:__ (Default **200**) Number of log messages to store.\n* __container:__ (Default **winston**) Name of the Redis container you wish your logs to be in.\n* __channel:__ (Default **None**) Name of the Redis channel to stream logs from.\n\n### Riak Transport\n\n_As of `winston@0.3.0` the Riak transport has been broken out into a new module: [winston-riak][11]._ Using it is just as easy:\n\n``` js\nconst { Riak } = require('winston-riak');\nlogger.add(new Riak(options));\n```\n\nIn addition to the options accepted by the [riak-js][12] [client][13], the Riak transport also accepts the following options. It is worth noting that the riak-js debug option is set to *false* by default:\n\n* __level:__ Level of messages that this transport should log.\n* __bucket:__ The name of the Riak bucket you wish your logs to be in or a function to generate bucket names dynamically.\n\n``` js\n  // Use a single bucket for all your logs\n  const singleBucketTransport = new Riak({ bucket: 'some-logs-go-here' });\n\n  // Generate a dynamic bucket based on the date and level\n  const dynamicBucketTransport = new Riak({\n    bucket: function (level, msg, meta, now) {\n      var d = new Date(now);\n      return level + [d.getDate(), d.getMonth(), d.getFullYear()].join('-');\n    }\n  });\n```\n\n\n## Find more Transports\n\nThere are more than 1000 packages on `npm` when [you search for] `winston`.\nThat's why we say it's a logger for just about everything\n\n[you search for]: https://www.npmjs.com/search?q=winston\n[0]: https://nodejs.org/api/stream.html#stream_class_stream_writable\n[1]: https://github.com/flatiron/winstond\n[2]: https://github.com/indexzero/winston-couchdb\n[3]: http://guide.couchdb.org/draft/design.html\n[4]: https://github.com/mranney/node_redis\n[5]: https://github.com/indexzero/winston-loggly\n[6]: http://nodejitsu.com\n[7]: https://github.com/nodejitsu/node-loggly\n[8]: http://loggly.com\n[9]: http://www.loggly.com/product/\n[10]: http://wiki.loggly.com/loggingfromcode\n[11]: https://github.com/indexzero/winston-riak\n[12]: http://riakjs.org\n[13]: https://github.com/frank06/riak-js/blob/master/src/http_client.coffee#L10\n[14]: http://github.com/indexzero/winston-mongodb\n[15]: http://github.com/appsattic/winston-simpledb\n[16]: http://github.com/wavded/winston-mail\n[17]: https://github.com/weaver/node-mail\n[18]: https://github.com/jesseditson/winston-sns\n[19]: https://github.com/namshi/winston-graylog2\n[20]: https://github.com/jorgebay/winston-cassandra\n[21]: https://github.com/jpoon/winston-azuretable\n[22]: https://github.com/rickcraig/winston-airbrake2\n[24]: https://github.com/sematext/winston-logsene\n[25]: https://github.com/timdp/winston-aws-cloudwatch\n[26]: https://github.com/lazywithclass/winston-cloudwatch\n[27]: https://github.com/kenperkins/winston-papertrail\n[28]: https://github.com/pkallos/winston-firehose\n[29]: https://www.npmjs.com/package/@google-cloud/logging-winston\n[30]: https://cloud.google.com/logging/\n[31]: https://github.com/joelee/winston-spark\n[32]: https://github.com/avens19/winston-sumologic-transport\n[33]: https://github.com/peteward44/winston-winlog2\n[34]: https://github.com/hakanostrom/winston-cloudant\n[35]: https://github.com/SerayaEryn/fast-file-rotate\n[36]: https://github.com/inspiredjw/winston-dynamodb\n[37]: https://github.com/logdna/logdna-winston\n[38]: https://github.com/marklai1998/datadog-logger-integrations\n[39]: https://github.com/TheAppleFreak/winston-slack-webhook-transport\n[40]: https://github.com/punkish/winston-better-sqlite3\n[41]: https://github.com/aandrewww/winston-transport-sentry-node\n[42]: https://github.com/kaminskypavel/winston-bigquery\n[43]: https://www.npmjs.com/package/winston-bigquery\n[44]: https://github.com/Quintinity/humio-winston\n[45]: https://github.com/datalust/winston-seq\n[46]: https://github.com/arpad1337/winston-console-transport-in-worker\n[47]: https://github.com/kimnetics/winston-newrelic-agent-transport\n[48]: https://github.com/loderunner/winston-transport-vscode\n"
  },
  {
    "path": "examples/color-message.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconst logger = module.exports = winston.createLogger({\n  transports: [new winston.transports.Console()],\n  format: winston.format.combine(\n    winston.format.colorize({ all: true }),\n    winston.format.simple()\n  )\n});\n\nlogger.log('info', 'This is an information message.');\n"
  },
  {
    "path": "examples/create-file.js",
    "content": "'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst winston = require('../lib/winston');\n\nconst filename = path.join(__dirname, 'created-logfile.log');\n\n//\n// Remove the file, ignoring any errors\n//\ntry { fs.unlinkSync(filename); }\ncatch (ex) { }\n\n//\n// Create a new winston logger instance with two tranports: Console, and File\n//\n//\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Console(),\n    new winston.transports.File({ filename })\n  ]\n});\n\nlogger.log('info', 'Hello created log files!', { 'foo': 'bar' });\n\nsetTimeout(function () {\n  //\n  // Remove the file, ignoring any errors\n  //\n  try { fs.unlinkSync(filename); }\n  catch (ex) { }\n}, 1000);\n"
  },
  {
    "path": "examples/custom-levels-colors.js",
    "content": "'use strict';\n\nconst winston = require('../lib/winston');\n\n//\n// Logging levels\n//\nconst config = {\n  levels: {\n    error: 0,\n    debug: 1,\n    warn: 2,\n    data: 3,\n    info: 4,\n    verbose: 5,\n    silly: 6,\n    custom: 7\n  },\n  colors: {\n    error: 'red',\n    debug: 'blue',\n    warn: 'yellow',\n    data: 'grey',\n    info: 'green',\n    verbose: 'cyan',\n    silly: 'magenta',\n    custom: 'yellow'\n  }\n};\n\nwinston.addColors(config.colors);\n\nconst logger = module.exports = winston.createLogger({\n  levels: config.levels,\n  format: winston.format.combine(\n    winston.format.colorize(),\n    winston.format.simple()\n  ),\n  transports: [\n    new winston.transports.Console()\n  ],\n  level: 'custom'\n});\n\nlogger.custom('hello')\n"
  },
  {
    "path": "examples/custom-levels.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconst myCustomLevels = {\n  levels: {\n    foo: 0,\n    bar: 1,\n    baz: 2,\n    foobar: 3\n  },\n  colors: {\n    foo: 'blue',\n    bar: 'green',\n    baz: 'yellow',\n    foobar: 'red'\n  }\n};\n\nconst customLevelLogger = winston.createLogger({\n  level: 'foobar',\n  levels: myCustomLevels.levels,\n  transports: [\n    new winston.transports.Console()\n  ]\n});\n\ncustomLevelLogger.foobar('some foobar level-ed message');\ncustomLevelLogger.baz('some baz level-ed message');\ncustomLevelLogger.bar('some bar level-ed message');\ncustomLevelLogger.foo('some foo level-ed message');\n"
  },
  {
    "path": "examples/custom-pretty-print.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconst logger = winston.createLogger({\n  format: winston.format.printf(info => {\n    return JSON.stringify(info)\n      .replace(/\\{/g, '< wow ')\n      .replace(/\\:/g, ' such ')\n      .replace(/\\}/g, ' >')\n  }),\n  transports: [\n    new winston.transports.Console(),\n  ]\n});\n\nlogger.info('Hello, this is a logging event with a custom pretty print',  { 'foo': 'bar' });\nlogger.info('Hello, this is a logging event with a custom pretty print2', { 'foo': 'bar' });\n\n"
  },
  {
    "path": "examples/custom-timestamp.js",
    "content": "const { format, createLogger, transports } = require('../');\n\nconst logger = createLogger({\n  format: format.combine(\n    format.label({ label: '[my-label]' }),\n    format.timestamp({\n      format: 'YYYY-MM-DD HH:mm:ss'\n    }),\n    //\n    // The simple format outputs\n    // `${level}: ${message} ${[Object with everything else]}`\n    //\n    format.simple()\n    //\n    // Alternatively you could use this custom printf format if you\n    // want to control where the timestamp comes in your final message.\n    // Try replacing `format.simple()` above with this:\n    //\n    // format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)\n  ),\n  transports: [\n    new transports.Console()\n  ]\n});\n\nlogger.info('Hello there. How are you?');\n"
  },
  {
    "path": "examples/custom-transport.js",
    "content": "\nconst { createLogger } = require('../');\nconst Transport = require('winston-transport');\n\n//\n// Inherit from `winston-transport` so you can take advantage\n// of the base functionality and `.exceptions.handle()`.\n//\nclass CustomTransport extends Transport {\n  constructor(opts) {\n    super(opts);\n\n    //\n    // Consume any custom options here. e.g.:\n    // - Connection information for databases\n    // - Authentication information for APIs (e.g. loggly, papertrail,\n    //   logentries, etc.).\n    //\n  }\n\n  log(info, callback) {\n    setImmediate(() => {\n      this.emit('logged', info);\n    });\n\n    // Perform the writing to the remote service\n\n    callback();\n  }\n};\n\nconst transport = new CustomTransport();\ntransport.on('logged', (info) => {\n  // Verification that log was called on your transport\n  console.log(`Logging! It's happening!`, info);\n});\n\n// Create a logger and consume an instance of your transport\nconst logger = createLogger({\n  transports: [transport]\n});\n\nlogger.info('hello')\n"
  },
  {
    "path": "examples/delete-level.js",
    "content": "'use strict';\n\nconst { createLogger, format, transports } = require('../');\nconst { combine, json } = format;\n\nconst severityLevelOnly = format(info => {\n  info.severityLevel = info.level;\n  delete info.level;\n  return info;\n});\n\nconst logger = createLogger({\n  format: combine(\n    severityLevelOnly(),\n    json()\n  ),\n  transports: [\n    new transports.Console(),\n  ]\n});\n\nlogger.info('This will print without { level }',  { 'foo': 'bar' });\nlogger.info('This will also print without { level }', { 'foo': 'bar' });\n\n"
  },
  {
    "path": "examples/errors.js",
    "content": "const { createLogger, format, transports } = require('../');\nconst { combine, errors, json } = format;\n\nconst logger = createLogger({\n  format: combine(\n    errors({ stack: true }),\n    json()\n  ),\n  transports: [\n    new transports.Console(),\n  ]\n});\n\nlogger.warn(new Error('Error passed as info'));\nlogger.log('error', new Error('Error passed as message'));\n\nlogger.warn('Maybe important error: ', new Error('Error passed as meta'));\nlogger.log('error', 'Important error: ', new Error('Error passed as meta'));\n\nlogger.error(new Error('Error as info'));\n"
  },
  {
    "path": "examples/exception.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\n//\n// TODO: THIS IS BROKEN & MUST BE FIXED BEFORE 3.0\n// This should output what was previously referred to\n// as \"humanReadableUncaughtExceptions\" by default.\n//\nconst logger = winston.createLogger({\n  format: winston.format.simple(),\n  transports: [\n    new winston.transports.Console({ handleExceptions: true })\n  ]\n});\n\nthrow new Error('Hello, winston!');\n"
  },
  {
    "path": "examples/file-maxsize.js",
    "content": "const path = require('path');\nconst { MESSAGE } = require('triple-beam');\nconst winston = require('../');\n\nconst logger = winston.createLogger({\n  level: 'info',\n  format: winston.format.printf(info => `${info.message}`),\n  transports: [\n    new winston.transports.File({\n      filename: path.join(__dirname, 'error.log'),\n      level: 'info',\n      maxsize: 500\n    })\n  ]\n});\n\n// Write 750 characters\nlogger.info(`test=${'a'.repeat(245)}`);\nlogger.info(`test=${'b'.repeat(245)}`);\nlogger.info(`test=${'c'.repeat(245)}`);\n\nsetTimeout(() => {\n  logger.info(`test=${'d'.repeat(245)}`);\n  logger.info(`test=${'e'.repeat(245)}`);\n  logger.info(`test=${'f'.repeat(245)}`);\n}, 2000);\n"
  },
  {
    "path": "examples/finish-event.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\n//\n// In winston@3.x both the Logger and the Transport are Node.js streams.\n// Node.js streams expose a `.end()` method that signals no more data will\\\n// be written. The `\"finish\"` event is emitted after `.end()` has been called\n// **AND** all data has been flushed (i.e. all your logs have been written).\n//\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Console()\n  ]\n});\n\nprocess.on('exit', function () {\n  console.log('Your process is exiting');\n});\n\nlogger.on('finish', function () {\n  console.log('Your logger is done logging');\n});\n\nlogger.log('info', 'Hello, this is a raw logging event',   { 'foo': 'bar' });\nlogger.log('info', 'Hello, this is a raw logging event 2', { 'foo': 'bar' });\n\nlogger.end();\n"
  },
  {
    "path": "examples/format-dynamic-content.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconst logger = module.exports = winston.createLogger({\n  transports: [new winston.transports.Console()],\n  format: winston.format.combine(\n    winston.format(function dynamicContent(info, opts) {\n      info.message = '[dynamic content] ' + info.message;\n      return info;\n    })(),\n    winston.format.simple()\n  )\n});\n\nlogger.log('info', 'This is an information message.');\n"
  },
  {
    "path": "examples/format-filter.js",
    "content": "const { createLogger, format, transports } = require('../');\n\n// Ignore log messages if the have { private: true }\nconst ignorePrivate = format((info, opts) => {\n  if (info.private) { return false; }\n  return info;\n});\n\nconst logger = createLogger({\n  format: format.combine(\n    ignorePrivate(),\n    format.json()\n  ),\n  transports: [new transports.Console()]\n});\n\n// Outputs: {\"level\":\"error\",\"message\":\"Public error to share\"}\nlogger.log({\n  level: 'error',\n  message: 'Public error to share'\n});\n\n// Messages with { private: true } will not be written when logged.\nlogger.log({\n  private: true,\n  level: 'error',\n  message: 'This is super secret - hide it.'\n});\n"
  },
  {
    "path": "examples/format-logger-and-transport.js",
    "content": "const fs = require('fs');\nconst winston = require('../');\nconst { createLogger, format, transports } = winston;\n\nconst logger = createLogger({\n  format: format.combine(\n    format.timestamp(),\n    format.simple()\n  ),\n  transports: [\n    new transports.Console({\n      format: format.combine(\n        format.timestamp(),\n        format.colorize(),\n        format.simple()\n      )\n    }),\n    new transports.Stream({\n      stream: fs.createWriteStream('./example.log')\n    })\n  ]\n})\n\nlogger.log({\n  level: 'info',\n  message: 'Check example.log – it will have no colors!'\n});\n"
  },
  {
    "path": "examples/format-mutate.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\n/*\n * Simple string mask. For example purposes only.\n */\nfunction maskCardNumbers(num) {\n  const str = num.toString();\n  const { length } = str;\n\n  return Array.from(str, (n, i) => {\n    return i < length - 4 ? '*' : n;\n  }).join('');\n}\n\n// Define the format that mutates the info object.\nconst maskFormat = winston.format(info => {\n  // You can CHANGE existing property values\n  if (info.creditCard) {\n    info.creditCard = maskCardNumbers(info.creditCard);\n  }\n\n  // You can also ADD NEW properties if you wish\n  info.hasCreditCard = !!info.creditCard;\n\n  return info;\n});\n\n// Then combine the format with other formats and make a logger\nconst logger = winston.createLogger({\n  format: winston.format.combine(\n    //\n    // Order is important here, the formats are called in the\n    // order they are passed to combine.\n    //\n    maskFormat(),\n    winston.format.json()\n  ),\n  transports: [\n    new winston.transports.Console()\n  ]\n});\n\nlogger.info('transaction ok', { creditCard: 123456789012345 });\n"
  },
  {
    "path": "examples/interpolation.js",
    "content": "'use strict';\n\nconst { createLogger, format, transports } = require('../');\nconst logger = createLogger({\n  format: format.combine(\n    format.splat(),\n    format.simple()\n  ),\n  transports: [\n    new transports.Console()\n  ]\n});\n\n// info: test message my string {}\nlogger.log('info', 'test message %s', 'my string');\n\n// info: test message my 123 {}\nlogger.log('info', 'test message %d', 123);\n\n// info: test message first second {number: 123}\nlogger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 });\n\n// prints \"Found error at %s\"\nlogger.info('Found %s at %s', 'error', new Date());\nlogger.info('Found %s at %s', 'error', new Error('chill winston'));\nlogger.info('Found %s at %s', 'error', /WUT/);\nlogger.info('Found %s at %s', 'error', true);\nlogger.info('Found %s at %s', 'error', 100.00);\nlogger.info('Found %s at %s', 'error', ['1, 2, 3']);\n\n"
  },
  {
    "path": "examples/json.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\n//\n// As of winston@3, the default logging format is JSON.\n//\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Console(),\n  ]\n});\n\nlogger.log('info', 'Hello, this is a raw logging event',   { 'foo': 'bar' });\nlogger.log('info', 'Hello, this is a raw logging event 2', { 'foo': 'bar' });\n"
  },
  {
    "path": "examples/levels.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconst defaultLevels = winston.createLogger({\n  level: 'silly',\n  format: winston.format.simple(),\n  transports: new winston.transports.Console()\n});\n\nfunction logAllLevels() {\n  Object.keys(winston.config.npm.levels).forEach(level => {\n    defaultLevels[level](`is logged when logger.level=\"${defaultLevels.level}\"`);\n  });\n}\n\nlogAllLevels();\n\n//\n// TODO: THIS IS BROKEN & MUST BE FIXED BEFORE 3.0\n// Logger.prototype.level must be a setter to set the\n// default level on all Transports.\n//\ndefaultLevels.level = 'error';\nlogAllLevels();\n"
  },
  {
    "path": "examples/metadata.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconst logger = winston.createLogger({\n  level: 'info',\n  format: winston.format.combine(\n    //\n    // Notice that both arguments have been combined into a single\n    // \"info\" object.\n    //\n    winston.format(function (info, opts) {\n      console.log(`{ reason: ${info.reason}, promise: ${info.promise} }`);\n      return info;\n    })(),\n    winston.format.json()\n  ),\n  transports: [\n    new winston.transports.Console()\n  ]\n});\n\nlogger.info('my message', { reason: 'whatever', promise: 'whenever' });\n"
  },
  {
    "path": "examples/quick-start.js",
    "content": "const { createLogger, format, transports } = require('../');\n\nconst logger = createLogger({\n  level: 'info',\n  format: format.combine(\n    format.timestamp({\n      format: 'YYYY-MM-DD HH:mm:ss'\n    }),\n    format.errors({ stack: true }),\n    format.splat(),\n    format.json()\n  ),\n  defaultMeta: { service: 'your-service-name' },\n  transports: [\n    //\n    // - Write to all logs with level `info` and below to `quick-start-combined.log`.\n    // - Write all logs error (and below) to `quick-start-error.log`.\n    //\n    new transports.File({ filename: 'quick-start-error.log', level: 'error' }),\n    new transports.File({ filename: 'quick-start-combined.log' })\n  ]\n});\n\n//\n// If we're not in production then **ALSO** log to the `console`\n// with the colorized simple format.\n//\nif (process.env.NODE_ENV !== 'production') {\n  logger.add(new transports.Console({\n    format: format.combine(\n      format.colorize(),\n      format.simple()\n    )\n  }));\n}\n\n// ***************\n// Allows for JSON logging\n// ***************\n\nlogger.log({\n  level: 'info',\n  message: 'Pass an object and this works',\n  additional: 'properties',\n  are: 'passed along'\n});\n\nlogger.info({\n  message: 'Use a helper method if you want',\n  additional: 'properties',\n  are: 'passed along'\n});\n\n// ***************\n// Allows for parameter-based logging\n// ***************\n\nlogger.log('info', 'Pass a message and this works', {\n  additional: 'properties',\n  are: 'passed along'\n});\n\nlogger.info('Use a helper method if you want', {\n  additional: 'properties',\n  are: 'passed along'\n});\n\n// ***************\n// Allows for string interpolation\n// ***************\n\n// info: test message my string {}\nlogger.log('info', 'test message %s', 'my string');\n\n// info: test message 123 {}\nlogger.log('info', 'test message %d', 123);\n\n// info: test message first second {number: 123}\nlogger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 });\n\n// prints \"Found error at %s\"\nlogger.info('Found %s at %s', 'error', new Date());\nlogger.info('Found %s at %s', 'error', new Error('chill winston'));\nlogger.info('Found %s at %s', 'error', /WUT/);\nlogger.info('Found %s at %s', 'error', true);\nlogger.info('Found %s at %s', 'error', 100.00);\nlogger.info('Found %s at %s', 'error', ['1, 2, 3']);\n\n// ***************\n// Allows for logging Error instances\n// ***************\n\nlogger.warn(new Error('Error passed as info'));\nlogger.log('error', new Error('Error passed as message'));\n\nlogger.warn('Maybe important error: ', new Error('Error passed as meta'));\nlogger.log('error', 'Important error: ', new Error('Error passed as meta'));\n\nlogger.error(new Error('Error as info'));\n"
  },
  {
    "path": "examples/ready-to-use-pattern.ts",
    "content": "const winston = require('../');\n\nconst config = {\n  levels: {\n    error: 0,\n    debug: 1,\n    warn: 2,\n    data: 3,\n    info: 4,\n    verbose: 5,\n    silly: 6\n  },\n  colors: {\n    error: 'red',\n    debug: 'blue',\n    warn: 'yellow',\n    data: 'magenta',\n    info: 'green',\n    verbose: 'cyan',\n    silly: 'grey'\n  }\n};\n\nwinston.addColors(config.colors);\nconst wLogger = (input: { logName: string; level: string }): winston.Logger =>\n  winston.createLogger({\n    levels: config.levels,\n    level: `${input.level}`,\n    transports: [\n      new winston.transports.Console({\n        level: `${input.level}`,\n\n        format: winston.format.combine(\n          winston.format.timestamp(),\n          winston.format.printf(\n            info =>\n              // https://stackoverflow.com/a/69044670/20358783 more detailLocaleString\n              `${new Date(info.timestamp).toLocaleDateString('tr-Tr', {\n                year: 'numeric',\n                month: '2-digit',\n                day: '2-digit',\n                hour: '2-digit',\n                minute: '2-digit'\n              })} ${info.level.toLocaleUpperCase()}: ${info.message}`\n          ),\n          winston.format.colorize({ all: true })\n        )\n      }),\n      new winston.transports.File({\n        filename: `./src/logs/${input.logName}/${input.logName}-Error.log`,\n        level: 'error',\n        format: winston.format.printf(\n          info =>\n            `${new Date(info.timestamp).toLocaleDateString('tr-Tr', {\n              year: 'numeric',\n              month: '2-digit',\n              day: '2-digit',\n              hour: '2-digit',\n              minute: '2-digit'\n            })} ${info.level.toLocaleUpperCase()}: ${info.message}`\n        )\n      }),\n      new winston.transports.File({\n        filename: `./src/logs/${input.logName}/${input.logName}-Warn.log`,\n        level: 'warn',\n        format: winston.format.printf(\n          info =>\n            `${new Date(info.timestamp).toLocaleDateString('tr-Tr', {\n              year: 'numeric',\n              month: '2-digit',\n              day: '2-digit',\n              hour: '2-digit',\n              minute: '2-digit'\n            })} ${info.level.toLocaleUpperCase()}: ${info.message}`\n        )\n      }),\n      new winston.transports.File({\n        filename: `./src/logs/${input.logName}/${input.logName}-All.log`,\n        level: 'silly',\n        format: winston.format.printf(\n          info =>\n            `${new Date(info.timestamp).toLocaleDateString('tr-Tr', {\n              year: 'numeric',\n              month: '2-digit',\n              day: '2-digit',\n              hour: '2-digit',\n              minute: '2-digit'\n            })} ${info.level.toLocaleUpperCase()}: ${info.message}`\n        )\n      }),\n\n      new winston.transports.File({\n        format: winston.format.printf(\n          info =>\n            `${new Date(info.timestamp).toLocaleDateString('tr-Tr', {\n              year: 'numeric',\n              month: '2-digit',\n              day: '2-digit',\n              hour: '2-digit',\n              minute: '2-digit'\n            })} ${info.level.toLocaleUpperCase()}: ${info.message}`\n        ),\n        filename: './src/logs/globalLog.log',\n        level: 'silly'\n      })\n    ]\n  });\n\nexport default wLogger;\n\n//const logger = wLogger({ logName: moduleName, level: logLevel })\n//logger.info('test')\n"
  },
  {
    "path": "examples/regular-expressions.js",
    "content": "'use strict';\n\nconst winston = require('../');\n\nconsole.info(new RegExp('a'));\n// prints \"/a/\"\n\n//\n// TODO: THIS IS BROKEN & MUST BE FIXED BEFORE 3.0?\n//\nwinston.info(new RegExp('a'));\n// prints \"info: /a/\"\n"
  },
  {
    "path": "examples/simple-stream.js",
    "content": "'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst winston = require('../lib/winston');\n\nconst filePath = path.join(__dirname, 'winston.log');\nconst stream = fs.createWriteStream(filePath);\n\nconst logger = winston.createLogger({\n  transports: [\n    new winston.transports.Stream({ stream })\n  ]\n});\n\nsetTimeout(() => {\n  logger.log({ level: 'info', message: 'foo' });\n  logger.log({ level: 'info', message: 'bar' });\n}, 1000);\n\nsetTimeout(() => {\n  try {\n    fs.unlinkSync(filePath); // eslint-disable-line no-sync\n  } catch (ex) {} // eslint-disable-line no-empty\n}, 2000);\n"
  },
  {
    "path": "examples/splat-message.js",
    "content": "const winston = require('../');\n\nconst loggers = {\n  splat: winston.createLogger({\n    level: 'info',\n    format: winston.format.combine(\n      winston.format.splat(),\n      winston.format.simple()\n    ),\n    transports: [new winston.transports.Console()],\n  }),\n  simple: winston.createLogger({\n    level: 'info',\n    format: winston.format.simple(),\n    transports: [new winston.transports.Console()],\n  })\n};\n\nconst meta = {\n  subject: 'Hello, World!',\n  message: 'This message is a unique property separate from implicit merging.',\n};\n\nloggers.simple.info('email.message is hidden', meta);\nloggers.simple.info('email.message is hidden %j\\n', meta);\n\nloggers.splat.info('This is overridden by meta', meta);\nloggers.splat.info('email.message is shown %j', meta);\n"
  },
  {
    "path": "examples/splat.js",
    "content": "const winston = require('../');\nlet { format } = winston;\n\n/*\n * Simple helper for stringifying all remaining\n * properties.\n */\nfunction rest(info) {\n  return JSON.stringify(Object.assign({}, info, {\n    level: undefined,\n    message: undefined,\n    splat: undefined,\n    label: undefined\n  }));\n}\n\nlet logger = winston.createLogger({\n  transports: [new winston.transports.Console({ level: 'info' })],\n  format: format.combine(\n    format.splat(),\n    format.printf(info => `[${info.label}] ${info.message} ${rest(info)}`)\n  )\n});\n\nlogger.log(\n  'info',\n  'any message',\n  {\n    label: 'label!',\n    extra: true\n  }\n);\n\nlogger.log(\n  'info',\n  'let\\'s %s some %s',\n  'interpolate',\n  'splat parameters',\n  {\n    label: 'label!',\n    extra: true\n  }\n);\n\nlogger.log(\n  'info',\n  'first is a string %s [[%j]]',\n  'behold a string',\n  { beAware: 'this will interpolate' },\n  {\n    label: 'label!',\n    extra: true\n  }\n);\n\nlogger.log(\n  'info',\n  'first is an object [[%j]]',\n  { beAware: 'this will interpolate' },\n  {\n    label: 'label!',\n    extra: true\n  }\n);\n\n//\n// Non-enumerable properties (such as \"message\" and \"stack\" in Error\n// instances) will not be merged into any `info`.\n//\nconst terr = new Error('lol please stop doing this');\nterr.label = 'error';\nterr.extra = true;\nlogger.log(\n  'info',\n  'any message',\n  terr\n);\n\nlogger.log(\n  'info',\n  'let\\'s %s some %s',\n  'interpolate',\n  'splat parameters',\n  terr\n);\n\n"
  },
  {
    "path": "index.d.ts",
    "content": "// Type definitions for winston 3.0\n// Project: https://github.com/winstonjs/winston\n\n/// <reference types=\"node\" />\n\nimport * as NodeJSStream from 'stream';\n\nimport * as logform from 'logform';\nimport * as Transport from 'winston-transport';\n\nimport * as Config from './lib/winston/config/index';\nimport * as Transports from './lib/winston/transports/index';\n\ndeclare namespace winston {\n  // Hoisted namespaces from other modules\n  export import format = logform.format;\n  export import Logform = logform;\n  export import config = Config;\n  export import transports = Transports;\n  export import transport = Transport;\n\n  class ExceptionHandler {\n    constructor(logger: Logger);\n    logger: Logger;\n    handlers: Map<any, any>;\n    catcher: Function | boolean;\n\n    handle(...transports: Transport[]): void;\n    unhandle(...transports: Transport[]): void;\n    getAllInfo(err: string | Error): object;\n    getProcessInfo(): object;\n    getOsInfo(): object;\n    getTrace(err: Error): object;\n  }\n\n  class RejectionHandler {\n    constructor(logger: Logger);\n    logger: Logger;\n    handlers: Map<any, any>;\n    catcher: Function | boolean;\n\n    handle(...transports: Transport[]): void;\n    unhandle(...transports: Transport[]): void;\n    getAllInfo(err: string | Error): object;\n    getProcessInfo(): object;\n    getOsInfo(): object;\n    getTrace(err: Error): object;\n  }\n\n  interface QueryOptions {\n    rows?: number;\n    limit?: number;\n    start?: number;\n    from?: Date;\n    until?: Date;\n    order?: 'asc' | 'desc';\n    fields: any;\n  }\n\n  class Profiler {\n    logger: Logger;\n    start: Number;\n    done(info?: any): boolean;\n  }\n\n  interface LogEntry {\n    level: string;\n    message: string;\n    [optionName: string]: any;\n  }\n\n  interface LogMethod {\n    (level: string, message: string, ...meta: any[]): Logger;\n    (entry: LogEntry): Logger;\n    (level: string, message: any): Logger;\n  }\n\n  interface LeveledLogMethod {\n    (message: string, ...meta: any[]): Logger;\n    (message: any): Logger;\n    (infoObject: object): Logger;\n  }\n\n  interface LoggerOptions {\n    levels?: Config.AbstractConfigSetLevels;\n    silent?: boolean;\n    format?: logform.Format;\n    level?: string;\n    exitOnError?: Function | boolean;\n    defaultMeta?: any;\n    transports?: Transport[] | Transport;\n    handleExceptions?: boolean;\n    handleRejections?: boolean;\n    exceptionHandlers?: any;\n    rejectionHandlers?: any;\n  }\n\n  class Logger extends NodeJSStream.Transform {\n    constructor(options?: LoggerOptions);\n\n    silent: boolean;\n    format: logform.Format;\n    levels: Config.AbstractConfigSetLevels;\n    level: string;\n    transports: Transport[];\n    exceptions: ExceptionHandler;\n    rejections: RejectionHandler;\n    profilers: object;\n    exitOnError: Function | boolean;\n    defaultMeta?: any;\n\n    log: LogMethod;\n    add(transport: Transport): this;\n    remove(transport: Transport): this;\n    clear(): this;\n    close(): this;\n\n    // for cli and npm levels\n    error: LeveledLogMethod;\n    warn: LeveledLogMethod;\n    help: LeveledLogMethod;\n    data: LeveledLogMethod;\n    info: LeveledLogMethod;\n    debug: LeveledLogMethod;\n    prompt: LeveledLogMethod;\n    http: LeveledLogMethod;\n    verbose: LeveledLogMethod;\n    input: LeveledLogMethod;\n    silly: LeveledLogMethod;\n\n    // for syslog levels only\n    emerg: LeveledLogMethod;\n    alert: LeveledLogMethod;\n    crit: LeveledLogMethod;\n    warning: LeveledLogMethod;\n    notice: LeveledLogMethod;\n\n    query(\n      options?: QueryOptions,\n      callback?: (err: Error, results: any) => void\n    ): any;\n    stream(options?: any): NodeJS.ReadableStream;\n\n    startTimer(): Profiler;\n    profile(id: string | number, meta?: Record<string, any>): this;\n\n    configure(options: LoggerOptions): void;\n\n    child(options: Object): this;\n\n    isLevelEnabled(level: string): boolean;\n    isErrorEnabled(): boolean;\n    isWarnEnabled(): boolean;\n    isInfoEnabled(): boolean;\n    isVerboseEnabled(): boolean;\n    isDebugEnabled(): boolean;\n    isSillyEnabled(): boolean;\n  }\n\n  class Container {\n    loggers: Map<string, Logger>;\n    options: LoggerOptions;\n\n    add(id: string, options?: LoggerOptions): Logger;\n    get(id: string, options?: LoggerOptions): Logger;\n    has(id: string): boolean;\n    close(id?: string): void;\n\n    constructor(options?: LoggerOptions);\n  }\n\n  let version: string;\n  let loggers: Container;\n\n  let addColors: (target: Config.AbstractConfigSetColors) => any;\n  let createLogger: (options?: LoggerOptions) => Logger;\n\n  // Pass-through npm level methods routed to the default logger.\n  let error: LeveledLogMethod;\n  let warn: LeveledLogMethod;\n  let info: LeveledLogMethod;\n  let http: LeveledLogMethod;\n  let verbose: LeveledLogMethod;\n  let debug: LeveledLogMethod;\n  let silly: LeveledLogMethod;\n\n  // Other pass-through methods routed to the default logger.\n  let log: LogMethod;\n  let query: (\n    options?: QueryOptions,\n    callback?: (err: Error, results: any) => void\n  ) => any;\n  let stream: (options?: any) => NodeJS.ReadableStream;\n  let add: (transport: Transport) => Logger;\n  let remove: (transport: Transport) => Logger;\n  let clear: () => Logger;\n  let startTimer: () => Profiler;\n  let profile: (id: string | number) => Logger;\n  let configure: (options: LoggerOptions) => void;\n  let child: (options: Object) => Logger;\n  let level: string;\n  let exceptions: ExceptionHandler;\n  let rejections: RejectionHandler;\n  let exitOnError: Function | boolean;\n  // let default: object;\n}\n\nexport = winston;\n"
  },
  {
    "path": "jest.config.js",
    "content": "/**\n * @type {import('@jest/types').Config.InitialOptions}\n */\nmodule.exports = {\n  collectCoverage: false,\n  collectCoverageFrom: [\n    '<rootDir>/lib/**/*.js'\n  ],\n  coverageDirectory: 'coverage',\n  testEnvironment: 'node',\n  testMatch: [\n    '<rootDir>/test/**/*.test.js'\n  ],\n  globalSetup: '<rootDir>/test/globalSetup.js',\n  silent: true,\n  verbose: true,\n  coverageThreshold: {\n    global: {\n      functions: 74.54,\n      lines: 72.48,\n      statements: 72.25,\n      branches: 64.04\n    }\n  }\n};\n\n"
  },
  {
    "path": "lib/winston/common.js",
    "content": "/**\n * common.js: Internal helper and utility functions for winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { format } = require('util');\n\n/**\n * Set of simple deprecation notices and a way to expose them for a set of\n * properties.\n * @type {Object}\n * @private\n */\nexports.warn = {\n  deprecated(prop) {\n    return () => {\n      throw new Error(format('{ %s } was removed in winston@3.0.0.', prop));\n    };\n  },\n  useFormat(prop) {\n    return () => {\n      throw new Error([\n        format('{ %s } was removed in winston@3.0.0.', prop),\n        'Use a custom winston.format = winston.format(function) instead.'\n      ].join('\\n'));\n    };\n  },\n  forFunctions(obj, type, props) {\n    props.forEach(prop => {\n      obj[prop] = exports.warn[type](prop);\n    });\n  },\n  forProperties(obj, type, props) {\n    props.forEach(prop => {\n      const notice = exports.warn[type](prop);\n      Object.defineProperty(obj, prop, {\n        get: notice,\n        set: notice\n      });\n    });\n  }\n};\n"
  },
  {
    "path": "lib/winston/config/index.d.ts",
    "content": "// Type definitions for winston 3.0\n// Project: https://github.com/winstonjs/winston\n\n/// <reference types=\"node\" />\n\ndeclare namespace winston {\n  interface AbstractConfigSetLevels {\n    [key: string]: number;\n  }\n\n  interface AbstractConfigSetColors {\n    [key: string]: string | string[];\n  }\n\n  interface AbstractConfigSet {\n    levels: AbstractConfigSetLevels;\n    colors: AbstractConfigSetColors;\n  }\n\n  interface CliConfigSetLevels extends AbstractConfigSetLevels {\n    error: number;\n    warn: number;\n    help: number;\n    data: number;\n    info: number;\n    debug: number;\n    prompt: number;\n    verbose: number;\n    input: number;\n    silly: number;\n  }\n\n  interface CliConfigSetColors extends AbstractConfigSetColors {\n    error: string | string[];\n    warn: string | string[];\n    help: string | string[];\n    data: string | string[];\n    info: string | string[];\n    debug: string | string[];\n    prompt: string | string[];\n    verbose: string | string[];\n    input: string | string[];\n    silly: string | string[];\n  }\n\n  interface NpmConfigSetLevels extends AbstractConfigSetLevels {\n    error: number;\n    warn: number;\n    info: number;\n    http: number;\n    verbose: number;\n    debug: number;\n    silly: number;\n  }\n\n  interface NpmConfigSetColors extends AbstractConfigSetColors {\n    error: string | string[];\n    warn: string | string[];\n    info: string | string[];\n    http: string | string[];\n    verbose: string | string[];\n    debug: string | string[];\n    silly: string | string[];\n  }\n\n  interface SyslogConfigSetLevels extends AbstractConfigSetLevels {\n    emerg: number;\n    alert: number;\n    crit: number;\n    error: number;\n    warning: number;\n    notice: number;\n    info: number;\n    debug: number;\n  }\n\n  interface SyslogConfigSetColors extends AbstractConfigSetColors {\n    emerg: string | string[];\n    alert: string | string[];\n    crit: string | string[];\n    error: string | string[];\n    warning: string | string[];\n    notice: string | string[];\n    info: string | string[];\n    debug: string | string[];\n  }\n\n  interface Config {\n    allColors: AbstractConfigSetColors;\n    cli: { levels: CliConfigSetLevels, colors: CliConfigSetColors };\n    npm: { levels: NpmConfigSetLevels, colors: NpmConfigSetColors };\n    syslog: { levels: SyslogConfigSetLevels, colors: SyslogConfigSetColors };\n\n    addColors(colors: AbstractConfigSetColors): void;\n  }\n}\n\ndeclare const winston: winston.Config;\nexport = winston;\n"
  },
  {
    "path": "lib/winston/config/index.js",
    "content": "/**\n * index.js: Default settings for all levels that winston knows about.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst logform = require('logform');\nconst { configs } = require('triple-beam');\n\n/**\n * Export config set for the CLI.\n * @type {Object}\n */\nexports.cli = logform.levels(configs.cli);\n\n/**\n * Export config set for npm.\n * @type {Object}\n */\nexports.npm = logform.levels(configs.npm);\n\n/**\n * Export config set for the syslog.\n * @type {Object}\n */\nexports.syslog = logform.levels(configs.syslog);\n\n/**\n * Hoist addColors from logform where it was refactored into in winston@3.\n * @type {Object}\n */\nexports.addColors = logform.levels;\n"
  },
  {
    "path": "lib/winston/container.js",
    "content": "/**\n * container.js: Inversion of control container for winston logger instances.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst createLogger = require('./create-logger');\n\n/**\n * Inversion of control container for winston logger instances.\n * @type {Container}\n */\nmodule.exports = class Container {\n  /**\n   * Constructor function for the Container object responsible for managing a\n   * set of `winston.Logger` instances based on string ids.\n   * @param {!Object} [options={}] - Default pass-thru options for Loggers.\n   */\n  constructor(options = {}) {\n    this.loggers = new Map();\n    this.options = options;\n  }\n\n  /**\n   * Retrieves a `winston.Logger` instance for the specified `id`. If an\n   * instance does not exist, one is created.\n   * @param {!string} id - The id of the Logger to get.\n   * @param {?Object} [options] - Options for the Logger instance.\n   * @returns {Logger} - A configured Logger instance with a specified id.\n   */\n  add(id, options) {\n    if (!this.loggers.has(id)) {\n      // Remark: Simple shallow clone for configuration options in case we pass\n      // in instantiated protoypal objects\n      options = Object.assign({}, options || this.options);\n      const existing = options.transports || this.options.transports;\n\n      // Remark: Make sure if we have an array of transports we slice it to\n      // make copies of those references.\n      if (existing) {\n        options.transports = Array.isArray(existing) ? existing.slice() : [existing];\n      } else {\n        options.transports = [];\n      }\n\n      const logger = createLogger(options);\n      logger.on('close', () => this._delete(id));\n      this.loggers.set(id, logger);\n    }\n\n    return this.loggers.get(id);\n  }\n\n  /**\n   * Retreives a `winston.Logger` instance for the specified `id`. If\n   * an instance does not exist, one is created.\n   * @param {!string} id - The id of the Logger to get.\n   * @param {?Object} [options] - Options for the Logger instance.\n   * @returns {Logger} - A configured Logger instance with a specified id.\n   */\n  get(id, options) {\n    return this.add(id, options);\n  }\n\n  /**\n   * Check if the container has a logger with the id.\n   * @param {?string} id - The id of the Logger instance to find.\n   * @returns {boolean} - Boolean value indicating if this instance has a\n   * logger with the specified `id`.\n   */\n  has(id) {\n    return !!this.loggers.has(id);\n  }\n\n  /**\n   * Closes a `Logger` instance with the specified `id` if it exists.\n   * If no `id` is supplied then all Loggers are closed.\n   * @param {?string} id - The id of the Logger instance to close.\n   * @returns {undefined}\n   */\n  close(id) {\n    if (id) {\n      return this._removeLogger(id);\n    }\n\n    this.loggers.forEach((val, key) => this._removeLogger(key));\n  }\n\n  /**\n   * Remove a logger based on the id.\n   * @param {!string} id - The id of the logger to remove.\n   * @returns {undefined}\n   * @private\n   */\n  _removeLogger(id) {\n    if (!this.loggers.has(id)) {\n      return;\n    }\n\n    const logger = this.loggers.get(id);\n    logger.close();\n    this._delete(id);\n  }\n\n  /**\n   * Deletes a `Logger` instance with the specified `id`.\n   * @param {!string} id - The id of the Logger instance to delete from\n   * container.\n   * @returns {undefined}\n   * @private\n   */\n  _delete(id) {\n    this.loggers.delete(id);\n  }\n};\n"
  },
  {
    "path": "lib/winston/create-logger.js",
    "content": "/**\n * create-logger.js: Logger factory for winston logger instances.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { LEVEL } = require('triple-beam');\nconst config = require('./config');\nconst Logger = require('./logger');\nconst debug = require('@dabh/diagnostics')('winston:create-logger');\n\nfunction isLevelEnabledFunctionName(level) {\n  return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';\n}\n\n/**\n * Create a new instance of a winston Logger. Creates a new\n * prototype for each instance.\n * @param {!Object} opts - Options for the created logger.\n * @returns {Logger} - A newly created logger instance.\n */\nmodule.exports = function (opts = {}) {\n  //\n  // Default levels: npm\n  //\n  opts.levels = opts.levels || config.npm.levels;\n\n  /**\n   * DerivedLogger to attach the logs level methods.\n   * @type {DerivedLogger}\n   * @extends {Logger}\n   */\n  class DerivedLogger extends Logger {\n    /**\n     * Create a new class derived logger for which the levels can be attached to\n     * the prototype of. This is a V8 optimization that is well know to increase\n     * performance of prototype functions.\n     * @param {!Object} options - Options for the created logger.\n     */\n    constructor(options) {\n      super(options);\n    }\n  }\n\n  const logger = new DerivedLogger(opts);\n\n  //\n  // Create the log level methods for the derived logger.\n  //\n  Object.keys(opts.levels).forEach(function (level) {\n    debug('Define prototype method for \"%s\"', level);\n    if (level === 'log') {\n      // eslint-disable-next-line no-console\n      console.warn('Level \"log\" not defined: conflicts with the method \"log\". Use a different level name.');\n      return;\n    }\n\n    //\n    // Define prototype methods for each log level e.g.:\n    // logger.log('info', msg) implies these methods are defined:\n    // - logger.info(msg)\n    // - logger.isInfoEnabled()\n    //\n    // Remark: to support logger.child this **MUST** be a function\n    // so it'll always be called on the instance instead of a fixed\n    // place in the prototype chain.\n    //\n    DerivedLogger.prototype[level] = function (...args) {\n      // Prefer any instance scope, but default to \"root\" logger\n      const self = this || logger;\n\n      // Optimize the hot-path which is the single object.\n      if (args.length === 1) {\n        const [msg] = args;\n        const info = msg && msg.message && msg || { message: msg };\n        info.level = info[LEVEL] = level;\n        self._addDefaultMeta(info);\n        self.write(info);\n        return (this || logger);\n      }\n\n      // When provided nothing assume the empty string\n      if (args.length === 0) {\n        self.log(level, '');\n        return self;\n      }\n\n      // Otherwise build argument list which could potentially conform to\n      // either:\n      // . v3 API: log(obj)\n      // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])\n      return self.log(level, ...args);\n    };\n\n    DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {\n      return (this || logger).isLevelEnabled(level);\n    };\n  });\n\n  return logger;\n};\n"
  },
  {
    "path": "lib/winston/exception-handler.js",
    "content": "/**\n * exception-handler.js: Object for handling uncaughtException events.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst os = require('os');\nconst asyncForEach = require('async/forEach');\nconst debug = require('@dabh/diagnostics')('winston:exception');\nconst once = require('one-time');\nconst stackTrace = require('stack-trace');\nconst ExceptionStream = require('./exception-stream');\n\n/**\n * Object for handling uncaughtException events.\n * @type {ExceptionHandler}\n */\nmodule.exports = class ExceptionHandler {\n  /**\n   * TODO: add contructor description\n   * @param {!Logger} logger - TODO: add param description\n   */\n  constructor(logger) {\n    if (!logger) {\n      throw new Error('Logger is required to handle exceptions');\n    }\n\n    this.logger = logger;\n    this.handlers = new Map();\n  }\n\n  /**\n   * Handles `uncaughtException` events for the current process by adding any\n   * handlers passed in.\n   * @returns {undefined}\n   */\n  handle(...args) {\n    args.forEach(arg => {\n      if (Array.isArray(arg)) {\n        return arg.forEach(handler => this._addHandler(handler));\n      }\n\n      this._addHandler(arg);\n    });\n\n    if (!this.catcher) {\n      this.catcher = this._uncaughtException.bind(this);\n      process.on('uncaughtException', this.catcher);\n    }\n  }\n\n  /**\n   * Removes any handlers to `uncaughtException` events for the current\n   * process. This does not modify the state of the `this.handlers` set.\n   * @returns {undefined}\n   */\n  unhandle() {\n    if (this.catcher) {\n      process.removeListener('uncaughtException', this.catcher);\n      this.catcher = false;\n\n      Array.from(this.handlers.values())\n        .forEach(wrapper => this.logger.unpipe(wrapper));\n    }\n  }\n\n  /**\n   * TODO: add method description\n   * @param {Error} err - Error to get information about.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getAllInfo(err) {\n    let message = null;\n    if (err) {\n      message = typeof err === 'string' ? err : err.message;\n    }\n\n    return {\n      error: err,\n      // TODO (indexzero): how do we configure this?\n      level: 'error',\n      message: [\n        `uncaughtException: ${(message || '(no error message)')}`,\n        err && err.stack || '  No stack trace'\n      ].join('\\n'),\n      stack: err && err.stack,\n      exception: true,\n      date: new Date().toString(),\n      process: this.getProcessInfo(),\n      os: this.getOsInfo(),\n      trace: this.getTrace(err)\n    };\n  }\n\n  /**\n   * Gets all relevant process information for the currently running process.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getProcessInfo() {\n    return {\n      pid: process.pid,\n      uid: process.getuid ? process.getuid() : null,\n      gid: process.getgid ? process.getgid() : null,\n      cwd: process.cwd(),\n      execPath: process.execPath,\n      version: process.version,\n      argv: process.argv,\n      memoryUsage: process.memoryUsage()\n    };\n  }\n\n  /**\n   * Gets all relevant OS information for the currently running process.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getOsInfo() {\n    return {\n      loadavg: os.loadavg(),\n      uptime: os.uptime()\n    };\n  }\n\n  /**\n   * Gets a stack trace for the specified error.\n   * @param {mixed} err - TODO: add param description.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getTrace(err) {\n    const trace = err ? stackTrace.parse(err) : stackTrace.get();\n    return trace.map(site => {\n      return {\n        column: site.getColumnNumber(),\n        file: site.getFileName(),\n        function: site.getFunctionName(),\n        line: site.getLineNumber(),\n        method: site.getMethodName(),\n        native: site.isNative()\n      };\n    });\n  }\n\n  /**\n   * Helper method to add a transport as an exception handler.\n   * @param {Transport} handler - The transport to add as an exception handler.\n   * @returns {void}\n   */\n  _addHandler(handler) {\n    if (!this.handlers.has(handler)) {\n      handler.handleExceptions = true;\n      const wrapper = new ExceptionStream(handler);\n      this.handlers.set(handler, wrapper);\n      this.logger.pipe(wrapper);\n    }\n  }\n\n  /**\n   * Logs all relevant information around the `err` and exits the current\n   * process.\n   * @param {Error} err - Error to handle\n   * @returns {mixed} - TODO: add return description.\n   * @private\n   */\n  _uncaughtException(err) {\n    const info = this.getAllInfo(err);\n    const handlers = this._getExceptionHandlers();\n    // Calculate if we should exit on this error\n    let doExit = typeof this.logger.exitOnError === 'function'\n      ? this.logger.exitOnError(err)\n      : this.logger.exitOnError;\n    let timeout;\n\n    if (!handlers.length && doExit) {\n      // eslint-disable-next-line no-console\n      console.warn('winston: exitOnError cannot be true with no exception handlers.');\n      // eslint-disable-next-line no-console\n      console.warn('winston: not exiting process.');\n      doExit = false;\n    }\n\n    function gracefulExit() {\n      debug('doExit', doExit);\n      debug('process._exiting', process._exiting);\n\n      if (doExit && !process._exiting) {\n        // Remark: Currently ignoring any exceptions from transports when\n        // catching uncaught exceptions.\n        if (timeout) {\n          clearTimeout(timeout);\n        }\n        // eslint-disable-next-line no-process-exit\n        process.exit(1);\n      }\n    }\n\n    if (!handlers || handlers.length === 0) {\n      return process.nextTick(gracefulExit);\n    }\n\n    // Log to all transports attempting to listen for when they are completed.\n    asyncForEach(handlers, (handler, next) => {\n      const done = once(next);\n      const transport = handler.transport || handler;\n\n      // Debug wrapping so that we can inspect what's going on under the covers.\n      function onDone(event) {\n        return () => {\n          debug(event);\n          done();\n        };\n      }\n\n      transport._ending = true;\n      transport.once('finish', onDone('finished'));\n      transport.once('error', onDone('error'));\n    }, () => doExit && gracefulExit());\n\n    this.logger.log(info);\n\n    // If exitOnError is true, then only allow the logging of exceptions to\n    // take up to `3000ms`.\n    if (doExit) {\n      timeout = setTimeout(gracefulExit, 3000);\n    }\n  }\n\n  /**\n   * Returns the list of transports and exceptionHandlers for this instance.\n   * @returns {Array} - List of transports and exceptionHandlers for this\n   * instance.\n   * @private\n   */\n  _getExceptionHandlers() {\n    // Remark (indexzero): since `logger.transports` returns all of the pipes\n    // from the _readableState of the stream we actually get the join of the\n    // explicit handlers and the implicit transports with\n    // `handleExceptions: true`\n    return this.logger.transports.filter(wrap => {\n      const transport = wrap.transport || wrap;\n      return transport.handleExceptions;\n    });\n  }\n};\n"
  },
  {
    "path": "lib/winston/exception-stream.js",
    "content": "/**\n * exception-stream.js: TODO: add file header handler.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { Writable } = require('readable-stream');\n\n/**\n * TODO: add class description.\n * @type {ExceptionStream}\n * @extends {Writable}\n */\nmodule.exports = class ExceptionStream extends Writable {\n  /**\n   * Constructor function for the ExceptionStream responsible for wrapping a\n   * TransportStream; only allowing writes of `info` objects with\n   * `info.exception` set to true.\n   * @param {!TransportStream} transport - Stream to filter to exceptions\n   */\n  constructor(transport) {\n    super({ objectMode: true });\n\n    if (!transport) {\n      throw new Error('ExceptionStream requires a TransportStream instance.');\n    }\n\n    // Remark (indexzero): we set `handleExceptions` here because it's the\n    // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers\n    this.handleExceptions = true;\n    this.transport = transport;\n  }\n\n  /**\n   * Writes the info object to our transport instance if (and only if) the\n   * `exception` property is set on the info.\n   * @param {mixed} info - TODO: add param description.\n   * @param {mixed} enc - TODO: add param description.\n   * @param {mixed} callback - TODO: add param description.\n   * @returns {mixed} - TODO: add return description.\n   * @private\n   */\n  _write(info, enc, callback) {\n    if (info.exception) {\n      return this.transport.log(info, callback);\n    }\n\n    callback();\n    return true;\n  }\n};\n"
  },
  {
    "path": "lib/winston/logger.js",
    "content": "/**\n * logger.js: TODO: add file header description.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { Stream, Transform } = require('readable-stream');\nconst asyncForEach = require('async/forEach');\nconst { LEVEL, SPLAT } = require('triple-beam');\nconst isStream = require('is-stream');\nconst ExceptionHandler = require('./exception-handler');\nconst RejectionHandler = require('./rejection-handler');\nconst LegacyTransportStream = require('winston-transport/legacy');\nconst Profiler = require('./profiler');\nconst { warn } = require('./common');\nconst config = require('./config');\n\n/**\n * Captures the number of format (i.e. %s strings) in a given string.\n * Based on `util.format`, see Node.js source:\n * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230\n * @type {RegExp}\n */\nconst formatRegExp = /%[scdjifoO%]/g;\n\n/**\n * TODO: add class description.\n * @type {Logger}\n * @extends {Transform}\n */\nclass Logger extends Transform {\n  /**\n   * Constructor function for the Logger object responsible for persisting log\n   * messages and metadata to one or more transports.\n   * @param {!Object} options - foo\n   */\n  constructor(options) {\n    super({ objectMode: true });\n    this.configure(options);\n  }\n\n  child(defaultRequestMetadata) {\n    const logger = this;\n    return Object.create(logger, {\n      write: {\n        value: function (info) {\n          const infoClone = Object.assign(\n            {},\n            defaultRequestMetadata,\n            info\n          );\n\n          // Object.assign doesn't copy inherited Error\n          // properties so we have to do that explicitly\n          //\n          // Remark (indexzero): we should remove this\n          // since the errors format will handle this case.\n          //\n          if (info instanceof Error) {\n            infoClone.stack = info.stack;\n            infoClone.message = info.message;\n            infoClone.cause = info.cause;\n          }\n\n          logger.write(infoClone);\n        }\n      }\n    });\n  }\n\n  /**\n   * This will wholesale reconfigure this instance by:\n   * 1. Resetting all transports. Older transports will be removed implicitly.\n   * 2. Set all other options including levels, colors, rewriters, filters,\n   *    exceptionHandlers, etc.\n   * @param {!Object} options - TODO: add param description.\n   * @returns {undefined}\n   */\n  configure({\n    silent,\n    format,\n    defaultMeta,\n    levels,\n    level = 'info',\n    exitOnError = true,\n    transports,\n    colors,\n    emitErrs,\n    formatters,\n    padLevels,\n    rewriters,\n    stripColors,\n    exceptionHandlers,\n    rejectionHandlers\n  } = {}) {\n    // Reset transports if we already have them\n    if (this.transports.length) {\n      this.clear();\n    }\n\n    this.silent = silent;\n    this.format = format || this.format || require('logform/json')();\n\n    this.defaultMeta = defaultMeta || null;\n    // Hoist other options onto this instance.\n    this.levels = levels || this.levels || config.npm.levels;\n    this.level = level;\n    if (this.exceptions) {\n      this.exceptions.unhandle();\n    }\n    if (this.rejections) {\n      this.rejections.unhandle();\n    }\n    this.exceptions = new ExceptionHandler(this);\n    this.rejections = new RejectionHandler(this);\n    this.profilers = {};\n    this.exitOnError = exitOnError;\n\n    // Add all transports we have been provided.\n    if (transports) {\n      transports = Array.isArray(transports) ? transports : [transports];\n      transports.forEach(transport => this.add(transport));\n    }\n\n    if (\n      colors ||\n      emitErrs ||\n      formatters ||\n      padLevels ||\n      rewriters ||\n      stripColors\n    ) {\n      throw new Error(\n        [\n          '{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.',\n          'Use a custom winston.format(function) instead.',\n          'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'\n        ].join('\\n')\n      );\n    }\n\n    if (exceptionHandlers) {\n      this.exceptions.handle(exceptionHandlers);\n    }\n    if (rejectionHandlers) {\n      this.rejections.handle(rejectionHandlers);\n    }\n  }\n\n  /* eslint-disable valid-jsdoc */\n  /**\n   * Helper method to get the highest logging level associated with a logger\n   *\n   * @returns { number | null } - The highest configured logging level, null\n   * for invalid configuration\n   */\n  getHighestLogLevel() {\n    // This can be null, if this.level has an invalid value\n    const configuredLevelValue = getLevelValue(this.levels, this.level);\n\n    // If there are no transports, return the level configured at the logger level\n    if (!this.transports || this.transports.length === 0) {\n      return configuredLevelValue;\n    }\n\n    return this.transports.reduce((max, transport) => {\n      const levelValue = getLevelValue(this.levels, transport.level);\n      return levelValue !== null && levelValue > max ? levelValue : max;\n    }, configuredLevelValue);\n  }\n\n  isLevelEnabled(level) {\n    const givenLevelValue = getLevelValue(this.levels, level);\n    if (givenLevelValue === null) {\n      return false;\n    }\n\n    const configuredLevelValue = getLevelValue(this.levels, this.level);\n    if (configuredLevelValue === null) {\n      return false;\n    }\n\n    if (!this.transports || this.transports.length === 0) {\n      return configuredLevelValue >= givenLevelValue;\n    }\n\n    const index = this.transports.findIndex(transport => {\n      let transportLevelValue = getLevelValue(this.levels, transport.level);\n      if (transportLevelValue === null) {\n        transportLevelValue = configuredLevelValue;\n      }\n      return transportLevelValue >= givenLevelValue;\n    });\n    return index !== -1;\n  }\n\n  /* eslint-disable valid-jsdoc */\n  /**\n   * Ensure backwards compatibility with a `log` method\n   * @param {mixed} level - Level the log message is written at.\n   * @param {mixed} msg - TODO: add param description.\n   * @param {mixed} meta - TODO: add param description.\n   * @returns {Logger} - TODO: add return description.\n   *\n   * @example\n   *    // Supports the existing API:\n   *    logger.log('info', 'Hello world', { custom: true });\n   *    logger.log('info', new Error('Yo, it\\'s on fire'));\n   *\n   *    // Requires winston.format.splat()\n   *    logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true });\n   *\n   *    // And the new API with a single JSON literal:\n   *    logger.log({ level: 'info', message: 'Hello world', custom: true });\n   *    logger.log({ level: 'info', message: new Error('Yo, it\\'s on fire') });\n   *\n   *    // Also requires winston.format.splat()\n   *    logger.log({\n   *      level: 'info',\n   *      message: '%s %d%%',\n   *      [SPLAT]: ['A string', 50],\n   *      meta: { thisIsMeta: true }\n   *    });\n   *\n   */\n  /* eslint-enable valid-jsdoc */\n  log(level, msg, ...splat) {\n    // eslint-disable-line max-params\n    // Optimize for the hotpath of logging JSON literals\n    if (arguments.length === 1) {\n      // Yo dawg, I heard you like levels ... seriously ...\n      // In this context the LHS `level` here is actually the `info` so read\n      // this as: info[LEVEL] = info.level;\n      level[LEVEL] = level.level;\n      this._addDefaultMeta(level);\n      this.write(level);\n      return this;\n    }\n\n    // Slightly less hotpath, but worth optimizing for.\n    if (arguments.length === 2) {\n      if (msg && typeof msg === 'object') {\n        msg[LEVEL] = msg.level = level;\n        this._addDefaultMeta(msg);\n        this.write(msg);\n        return this;\n      }\n\n      msg = { [LEVEL]: level, level, message: msg };\n      this._addDefaultMeta(msg);\n      this.write(msg);\n      return this;\n    }\n\n    const [meta] = splat;\n    if (typeof meta === 'object' && meta !== null) {\n      // Extract tokens, if none available default to empty array to\n      // ensure consistancy in expected results\n      const tokens = msg && msg.match && msg.match(formatRegExp);\n\n      if (!tokens) {\n        const info = Object.assign({}, this.defaultMeta, meta, {\n          [LEVEL]: level,\n          [SPLAT]: splat,\n          level,\n          message: msg\n        });\n\n        if (meta.message) info.message = `${info.message} ${meta.message}`;\n        if (meta.stack) info.stack = meta.stack;\n        if (meta.cause) info.cause = meta.cause;\n\n        this.write(info);\n        return this;\n      }\n    }\n\n    this.write(Object.assign({}, this.defaultMeta, {\n      [LEVEL]: level,\n      [SPLAT]: splat,\n      level,\n      message: msg\n    }));\n\n    return this;\n  }\n\n  /**\n   * Pushes data so that it can be picked up by all of our pipe targets.\n   * @param {mixed} info - TODO: add param description.\n   * @param {mixed} enc - TODO: add param description.\n   * @param {mixed} callback - Continues stream processing.\n   * @returns {undefined}\n   * @private\n   */\n  _transform(info, enc, callback) {\n    if (this.silent) {\n      return callback();\n    }\n\n    // [LEVEL] is only soft guaranteed to be set here since we are a proper\n    // stream. It is likely that `info` came in through `.log(info)` or\n    // `.info(info)`. If it is not defined, however, define it.\n    // This LEVEL symbol is provided by `triple-beam` and also used in:\n    // - logform\n    // - winston-transport\n    // - abstract-winston-transport\n    if (!info[LEVEL]) {\n      info[LEVEL] = info.level;\n    }\n\n    // Remark: really not sure what to do here, but this has been reported as\n    // very confusing by pre winston@2.0.0 users as quite confusing when using\n    // custom levels.\n    if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {\n      // eslint-disable-next-line no-console\n      console.error('[winston] Unknown logger level: %s', info[LEVEL]);\n    }\n\n    // Remark: not sure if we should simply error here.\n    if (!this._readableState.pipes) {\n      // eslint-disable-next-line no-console\n      console.error(\n        '[winston] Attempt to write logs with no transports, which can increase memory usage: %j',\n        info\n      );\n    }\n\n    // Here we write to the `format` pipe-chain, which on `readable` above will\n    // push the formatted `info` Object onto the buffer for this instance. We trap\n    // (and re-throw) any errors generated by the user-provided format, but also\n    // guarantee that the streams callback is invoked so that we can continue flowing.\n    try {\n      this.push(this.format.transform(info, this.format.options));\n    } finally {\n      this._writableState.sync = false;\n      // eslint-disable-next-line callback-return\n      callback();\n    }\n  }\n\n  /**\n   * Delays the 'finish' event until all transport pipe targets have\n   * also emitted 'finish' or are already finished.\n   * @param {mixed} callback - Continues stream processing.\n   */\n  _final(callback) {\n    const transports = this.transports.slice();\n    asyncForEach(\n      transports,\n      (transport, next) => {\n        if (!transport || transport.finished) return setImmediate(next);\n        transport.once('finish', next);\n        transport.end();\n      },\n      callback\n    );\n  }\n\n  /**\n   * Adds the transport to this logger instance by piping to it.\n   * @param {mixed} transport - TODO: add param description.\n   * @returns {Logger} - TODO: add return description.\n   */\n  add(transport) {\n    // Support backwards compatibility with all existing `winston < 3.x.x`\n    // transports which meet one of two criteria:\n    // 1. They inherit from winston.Transport in  < 3.x.x which is NOT a stream.\n    // 2. They expose a log method which has a length greater than 2 (i.e. more then\n    //    just `log(info, callback)`.\n    const target =\n      !isStream(transport) || transport.log.length > 2\n        ? new LegacyTransportStream({ transport })\n        : transport;\n\n    if (!target._writableState || !target._writableState.objectMode) {\n      throw new Error(\n        'Transports must WritableStreams in objectMode. Set { objectMode: true }.'\n      );\n    }\n\n    // Listen for the `error` event and the `warn` event on the new Transport.\n    this._onEvent('error', target);\n    this._onEvent('warn', target);\n    this.pipe(target);\n\n    if (transport.handleExceptions) {\n      this.exceptions.handle();\n    }\n\n    if (transport.handleRejections) {\n      this.rejections.handle();\n    }\n\n    return this;\n  }\n\n  /**\n   * Removes the transport from this logger instance by unpiping from it.\n   * @param {mixed} transport - TODO: add param description.\n   * @returns {Logger} - TODO: add return description.\n   */\n  remove(transport) {\n    if (!transport) return this;\n    let target = transport;\n    if (!isStream(transport) || transport.log.length > 2) {\n      target = this.transports.filter(\n        match => match.transport === transport\n      )[0];\n    }\n\n    if (target) {\n      this.unpipe(target);\n    }\n    return this;\n  }\n\n  /**\n   * Removes all transports from this logger instance.\n   * @returns {Logger} - TODO: add return description.\n   */\n  clear() {\n    this.unpipe();\n    return this;\n  }\n\n  /**\n   * Cleans up resources (streams, event listeners) for all transports\n   * associated with this instance (if necessary).\n   * @returns {Logger} - TODO: add return description.\n   */\n  close() {\n    this.exceptions.unhandle();\n    this.rejections.unhandle();\n    this.clear();\n    this.emit('close');\n    return this;\n  }\n\n  /**\n   * Sets the `target` levels specified on this instance.\n   * @param {Object} Target levels to use on this instance.\n   */\n  setLevels() {\n    warn.deprecated('setLevels');\n  }\n\n  /**\n   * Queries the all transports for this instance with the specified `options`.\n   * This will aggregate each transport's results into one object containing\n   * a property per transport.\n   * @param {Object} options - Query options for this instance.\n   * @param {function} callback - Continuation to respond to when complete.\n   */\n  query(options, callback) {\n    if (typeof options === 'function') {\n      callback = options;\n      options = {};\n    }\n\n    options = options || {};\n    const results = {};\n    const queryObject = Object.assign({}, options.query || {});\n\n    // Helper function to query a single transport\n    function queryTransport(transport, next) {\n      if (options.query && typeof transport.formatQuery === 'function') {\n        options.query = transport.formatQuery(queryObject);\n      }\n\n      transport.query(options, (err, res) => {\n        if (err) {\n          return next(err);\n        }\n\n        if (typeof transport.formatResults === 'function') {\n          res = transport.formatResults(res, options.format);\n        }\n\n        next(null, res);\n      });\n    }\n\n    // Helper function to accumulate the results from `queryTransport` into\n    // the `results`.\n    function addResults(transport, next) {\n      queryTransport(transport, (err, result) => {\n        // queryTransport could potentially invoke the callback multiple times\n        // since Transport code can be unpredictable.\n        if (next) {\n          result = err || result;\n          if (result) {\n            results[transport.name] = result;\n          }\n\n          // eslint-disable-next-line callback-return\n          next();\n        }\n\n        next = null;\n      });\n    }\n\n    // Iterate over the transports in parallel setting the appropriate key in\n    // the `results`.\n    asyncForEach(\n      this.transports.filter(transport => !!transport.query),\n      addResults,\n      () => callback(null, results)\n    );\n  }\n\n  /**\n   * Returns a log stream for all transports. Options object is optional.\n   * @param{Object} options={} - Stream options for this instance.\n   * @returns {Stream} - TODO: add return description.\n   */\n  stream(options = {}) {\n    const out = new Stream();\n    const streams = [];\n\n    out._streams = streams;\n    out.destroy = () => {\n      let i = streams.length;\n      while (i--) {\n        streams[i].destroy();\n      }\n    };\n\n    // Create a list of all transports for this instance.\n    this.transports\n      .filter(transport => !!transport.stream)\n      .forEach(transport => {\n        const str = transport.stream(options);\n        if (!str) {\n          return;\n        }\n\n        streams.push(str);\n\n        str.on('log', log => {\n          log.transport = log.transport || [];\n          log.transport.push(transport.name);\n          out.emit('log', log);\n        });\n\n        str.on('error', err => {\n          err.transport = err.transport || [];\n          err.transport.push(transport.name);\n          out.emit('error', err);\n        });\n      });\n\n    return out;\n  }\n\n  /**\n   * Returns an object corresponding to a specific timing. When done is called\n   * the timer will finish and log the duration. e.g.:\n   * @returns {Profile} - TODO: add return description.\n   * @example\n   *    const timer = winston.startTimer()\n   *    setTimeout(() => {\n   *      timer.done({\n   *        message: 'Logging message'\n   *      });\n   *    }, 1000);\n   */\n  startTimer() {\n    return new Profiler(this);\n  }\n\n  /**\n   * Tracks the time inbetween subsequent calls to this method with the same\n   * `id` parameter. The second call to this method will log the difference in\n   * milliseconds along with the message.\n   * @param {string} id Unique id of the profiler\n   * @returns {Logger} - TODO: add return description.\n   */\n  profile(id, ...args) {\n    const time = Date.now();\n    if (this.profilers[id]) {\n      const timeEnd = this.profilers[id];\n      delete this.profilers[id];\n\n      // Attempt to be kind to users if they are still using older APIs.\n      if (typeof args[args.length - 2] === 'function') {\n        // eslint-disable-next-line no-console\n        console.warn(\n          'Callback function no longer supported as of winston@3.0.0'\n        );\n        args.pop();\n      }\n\n      // Set the duration property of the metadata\n      const info = typeof args[args.length - 1] === 'object' ? args.pop() : {};\n      info.level = info.level || 'info';\n      info.durationMs = time - timeEnd;\n      info.message = info.message || id;\n      return this.write(info);\n    }\n\n    this.profilers[id] = time;\n    return this;\n  }\n\n  /**\n   * Backwards compatibility to `exceptions.handle` in winston < 3.0.0.\n   * @returns {undefined}\n   * @deprecated\n   */\n  handleExceptions(...args) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      'Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()'\n    );\n    this.exceptions.handle(...args);\n  }\n\n  /**\n   * Backwards compatibility to `exceptions.handle` in winston < 3.0.0.\n   * @returns {undefined}\n   * @deprecated\n   */\n  unhandleExceptions(...args) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      'Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()'\n    );\n    this.exceptions.unhandle(...args);\n  }\n\n  /**\n   * Throw a more meaningful deprecation notice\n   * @throws {Error} - TODO: add throws description.\n   */\n  cli() {\n    throw new Error(\n      [\n        'Logger.cli() was removed in winston@3.0.0',\n        'Use a custom winston.formats.cli() instead.',\n        'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'\n      ].join('\\n')\n    );\n  }\n\n  /**\n   * Bubbles the `event` that occured on the specified `transport` up\n   * from this instance.\n   * @param {string} event - The event that occured\n   * @param {Object} transport - Transport on which the event occured\n   * @private\n   */\n  _onEvent(event, transport) {\n    function transportEvent(err) {\n      // https://github.com/winstonjs/winston/issues/1364\n      if (event === 'error' && !this.transports.includes(transport)) {\n        this.add(transport);\n      }\n      this.emit(event, err, transport);\n    }\n\n    if (!transport['__winston' + event]) {\n      transport['__winston' + event] = transportEvent.bind(this);\n      transport.on(event, transport['__winston' + event]);\n    }\n  }\n\n  _addDefaultMeta(msg) {\n    if (this.defaultMeta) {\n      Object.assign(msg, this.defaultMeta);\n    }\n  }\n}\n\nfunction getLevelValue(levels, level) {\n  const value = levels[level];\n  if (!value && value !== 0) {\n    return null;\n  }\n  return value;\n}\n\n/**\n * Represents the current readableState pipe targets for this Logger instance.\n * @type {Array|Object}\n */\nObject.defineProperty(Logger.prototype, 'transports', {\n  configurable: false,\n  enumerable: true,\n  get() {\n    const { pipes } = this._readableState;\n    return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;\n  }\n});\n\nmodule.exports = Logger;\n"
  },
  {
    "path": "lib/winston/profiler.js",
    "content": "/**\n * profiler.js: TODO: add file header description.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n/**\n * TODO: add class description.\n * @type {Profiler}\n * @private\n */\nclass Profiler {\n  /**\n   * Constructor function for the Profiler instance used by\n   * `Logger.prototype.startTimer`. When done is called the timer will finish\n   * and log the duration.\n   * @param {!Logger} logger - TODO: add param description.\n   * @private\n   */\n  constructor(logger) {\n    const Logger = require('./logger');\n    if (typeof logger !== 'object' || Array.isArray(logger) || !(logger instanceof Logger)) {\n      throw new Error('Logger is required for profiling');\n    } else {\n      this.logger = logger;\n      this.start = Date.now();\n    }\n  }\n\n  /**\n   * Ends the current timer (i.e. Profiler) instance and logs the `msg` along\n   * with the duration since creation.\n   * @returns {mixed} - TODO: add return description.\n   * @private\n   */\n  done(...args) {\n    if (typeof args[args.length - 1] === 'function') {\n      // eslint-disable-next-line no-console\n      console.warn('Callback function no longer supported as of winston@3.0.0');\n      args.pop();\n    }\n\n    const info = typeof args[args.length - 1] === 'object' ? args.pop() : {};\n    info.level = info.level || 'info';\n    info.durationMs = (Date.now()) - this.start;\n\n    return this.logger.write(info);\n  }\n}\n\nmodule.exports = Profiler;\n"
  },
  {
    "path": "lib/winston/rejection-handler.js",
    "content": "/**\n * exception-handler.js: Object for handling uncaughtException events.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst os = require('os');\nconst asyncForEach = require('async/forEach');\nconst debug = require('@dabh/diagnostics')('winston:rejection');\nconst once = require('one-time');\nconst stackTrace = require('stack-trace');\nconst RejectionStream = require('./rejection-stream');\n\n/**\n * Object for handling unhandledRejection events.\n * @type {RejectionHandler}\n */\nmodule.exports = class RejectionHandler {\n  /**\n   * TODO: add contructor description\n   * @param {!Logger} logger - TODO: add param description\n   */\n  constructor(logger) {\n    if (!logger) {\n      throw new Error('Logger is required to handle rejections');\n    }\n\n    this.logger = logger;\n    this.handlers = new Map();\n  }\n\n  /**\n   * Handles `unhandledRejection` events for the current process by adding any\n   * handlers passed in.\n   * @returns {undefined}\n   */\n  handle(...args) {\n    args.forEach(arg => {\n      if (Array.isArray(arg)) {\n        return arg.forEach(handler => this._addHandler(handler));\n      }\n\n      this._addHandler(arg);\n    });\n\n    if (!this.catcher) {\n      this.catcher = this._unhandledRejection.bind(this);\n      process.on('unhandledRejection', this.catcher);\n    }\n  }\n\n  /**\n   * Removes any handlers to `unhandledRejection` events for the current\n   * process. This does not modify the state of the `this.handlers` set.\n   * @returns {undefined}\n   */\n  unhandle() {\n    if (this.catcher) {\n      process.removeListener('unhandledRejection', this.catcher);\n      this.catcher = false;\n\n      Array.from(this.handlers.values()).forEach(wrapper =>\n        this.logger.unpipe(wrapper)\n      );\n    }\n  }\n\n  /**\n   * TODO: add method description\n   * @param {Error} err - Error to get information about.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getAllInfo(err) {\n    let message = null;\n    if (err) {\n      message = typeof err === 'string' ? err : err.message;\n    }\n\n    return {\n      error: err,\n      // TODO (indexzero): how do we configure this?\n      level: 'error',\n      message: [\n        `unhandledRejection: ${message || '(no error message)'}`,\n        err && err.stack || '  No stack trace'\n      ].join('\\n'),\n      stack: err && err.stack,\n      rejection: true,\n      date: new Date().toString(),\n      process: this.getProcessInfo(),\n      os: this.getOsInfo(),\n      trace: this.getTrace(err)\n    };\n  }\n\n  /**\n   * Gets all relevant process information for the currently running process.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getProcessInfo() {\n    return {\n      pid: process.pid,\n      uid: process.getuid ? process.getuid() : null,\n      gid: process.getgid ? process.getgid() : null,\n      cwd: process.cwd(),\n      execPath: process.execPath,\n      version: process.version,\n      argv: process.argv,\n      memoryUsage: process.memoryUsage()\n    };\n  }\n\n  /**\n   * Gets all relevant OS information for the currently running process.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getOsInfo() {\n    return {\n      loadavg: os.loadavg(),\n      uptime: os.uptime()\n    };\n  }\n\n  /**\n   * Gets a stack trace for the specified error.\n   * @param {mixed} err - TODO: add param description.\n   * @returns {mixed} - TODO: add return description.\n   */\n  getTrace(err) {\n    const trace = err ? stackTrace.parse(err) : stackTrace.get();\n    return trace.map(site => {\n      return {\n        column: site.getColumnNumber(),\n        file: site.getFileName(),\n        function: site.getFunctionName(),\n        line: site.getLineNumber(),\n        method: site.getMethodName(),\n        native: site.isNative()\n      };\n    });\n  }\n\n  /**\n   * Helper method to add a transport as an exception handler.\n   * @param {Transport} handler - The transport to add as an exception handler.\n   * @returns {void}\n   */\n  _addHandler(handler) {\n    if (!this.handlers.has(handler)) {\n      handler.handleRejections = true;\n      const wrapper = new RejectionStream(handler);\n      this.handlers.set(handler, wrapper);\n      this.logger.pipe(wrapper);\n    }\n  }\n\n  /**\n   * Logs all relevant information around the `err` and exits the current\n   * process.\n   * @param {Error} err - Error to handle\n   * @returns {mixed} - TODO: add return description.\n   * @private\n   */\n  _unhandledRejection(err) {\n    const info = this.getAllInfo(err);\n    const handlers = this._getRejectionHandlers();\n    // Calculate if we should exit on this error\n    let doExit =\n      typeof this.logger.exitOnError === 'function'\n        ? this.logger.exitOnError(err)\n        : this.logger.exitOnError;\n    let timeout;\n\n    if (!handlers.length && doExit) {\n      // eslint-disable-next-line no-console\n      console.warn('winston: exitOnError cannot be true with no rejection handlers.');\n      // eslint-disable-next-line no-console\n      console.warn('winston: not exiting process.');\n      doExit = false;\n    }\n\n    function gracefulExit() {\n      debug('doExit', doExit);\n      debug('process._exiting', process._exiting);\n\n      if (doExit && !process._exiting) {\n        // Remark: Currently ignoring any rejections from transports when\n        // catching unhandled rejections.\n        if (timeout) {\n          clearTimeout(timeout);\n        }\n        // eslint-disable-next-line no-process-exit\n        process.exit(1);\n      }\n    }\n\n    if (!handlers || handlers.length === 0) {\n      return process.nextTick(gracefulExit);\n    }\n\n    // Log to all transports attempting to listen for when they are completed.\n    asyncForEach(\n      handlers,\n      (handler, next) => {\n        const done = once(next);\n        const transport = handler.transport || handler;\n\n        // Debug wrapping so that we can inspect what's going on under the covers.\n        function onDone(event) {\n          return () => {\n            debug(event);\n            done();\n          };\n        }\n\n        transport._ending = true;\n        transport.once('finish', onDone('finished'));\n        transport.once('error', onDone('error'));\n      },\n      () => doExit && gracefulExit()\n    );\n\n    this.logger.log(info);\n\n    // If exitOnError is true, then only allow the logging of exceptions to\n    // take up to `3000ms`.\n    if (doExit) {\n      timeout = setTimeout(gracefulExit, 3000);\n    }\n  }\n\n  /**\n   * Returns the list of transports and exceptionHandlers for this instance.\n   * @returns {Array} - List of transports and exceptionHandlers for this\n   * instance.\n   * @private\n   */\n  _getRejectionHandlers() {\n    // Remark (indexzero): since `logger.transports` returns all of the pipes\n    // from the _readableState of the stream we actually get the join of the\n    // explicit handlers and the implicit transports with\n    // `handleRejections: true`\n    return this.logger.transports.filter(wrap => {\n      const transport = wrap.transport || wrap;\n      return transport.handleRejections;\n    });\n  }\n};\n"
  },
  {
    "path": "lib/winston/rejection-stream.js",
    "content": "/**\n * rejection-stream.js: TODO: add file header handler.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { Writable } = require('readable-stream');\n\n/**\n * TODO: add class description.\n * @type {RejectionStream}\n * @extends {Writable}\n */\nmodule.exports = class RejectionStream extends Writable {\n  /**\n   * Constructor function for the RejectionStream responsible for wrapping a\n   * TransportStream; only allowing writes of `info` objects with\n   * `info.rejection` set to true.\n   * @param {!TransportStream} transport - Stream to filter to rejections\n   */\n  constructor(transport) {\n    super({ objectMode: true });\n\n    if (!transport) {\n      throw new Error('RejectionStream requires a TransportStream instance.');\n    }\n\n    this.handleRejections = true;\n    this.transport = transport;\n  }\n\n  /**\n   * Writes the info object to our transport instance if (and only if) the\n   * `rejection` property is set on the info.\n   * @param {mixed} info - TODO: add param description.\n   * @param {mixed} enc - TODO: add param description.\n   * @param {mixed} callback - TODO: add param description.\n   * @returns {mixed} - TODO: add return description.\n   * @private\n   */\n  _write(info, enc, callback) {\n    if (info.rejection) {\n      return this.transport.log(info, callback);\n    }\n\n    callback();\n    return true;\n  }\n};\n"
  },
  {
    "path": "lib/winston/tail-file.js",
    "content": "/**\n * tail-file.js: TODO: add file header description.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst fs = require('fs');\nconst { StringDecoder } = require('string_decoder');\nconst { Stream } = require('readable-stream');\n\n/**\n * Simple no-op function.\n * @returns {undefined}\n */\nfunction noop() {}\n\n/**\n * TODO: add function description.\n * @param {Object} options - Options for tail.\n * @param {function} iter - Iterator function to execute on every line.\n* `tail -f` a file. Options must include file.\n * @returns {mixed} - TODO: add return description.\n */\nmodule.exports = (options, iter) => {\n  const buffer = Buffer.alloc(64 * 1024);\n  const decode = new StringDecoder('utf8');\n  const stream = new Stream();\n  let buff = '';\n  let pos = 0;\n  let row = 0;\n\n  if (options.start === -1) {\n    delete options.start;\n  }\n\n  stream.readable = true;\n  stream.destroy = () => {\n    stream.destroyed = true;\n    stream.emit('end');\n    stream.emit('close');\n  };\n\n  fs.open(options.file, 'a+', '0644', (err, fd) => {\n    if (err) {\n      if (!iter) {\n        stream.emit('error', err);\n      } else {\n        iter(err);\n      }\n      stream.destroy();\n      return;\n    }\n\n    (function read() {\n      if (stream.destroyed) {\n        fs.close(fd, noop);\n        return;\n      }\n\n      return fs.read(fd, buffer, 0, buffer.length, pos, (error, bytes) => {\n        if (error) {\n          if (!iter) {\n            stream.emit('error', error);\n          } else {\n            iter(error);\n          }\n          stream.destroy();\n          return;\n        }\n\n        if (!bytes) {\n          if (buff) {\n            // eslint-disable-next-line eqeqeq\n            if (options.start == null || row > options.start) {\n              if (!iter) {\n                stream.emit('line', buff);\n              } else {\n                iter(null, buff);\n              }\n            }\n            row++;\n            buff = '';\n          }\n          return setTimeout(read, 1000);\n        }\n\n        let data = decode.write(buffer.slice(0, bytes));\n        if (!iter) {\n          stream.emit('data', data);\n        }\n\n        data = (buff + data).split(/\\n+/);\n\n        const l = data.length - 1;\n        let i = 0;\n\n        for (; i < l; i++) {\n          // eslint-disable-next-line eqeqeq\n          if (options.start == null || row > options.start) {\n            if (!iter) {\n              stream.emit('line', data[i]);\n            } else {\n              iter(null, data[i]);\n            }\n          }\n          row++;\n        }\n\n        buff = data[l];\n        pos += bytes;\n        return read();\n      });\n    }());\n  });\n\n  if (!iter) {\n    return stream;\n  }\n\n  return stream.destroy;\n};\n"
  },
  {
    "path": "lib/winston/transports/console.js",
    "content": "/* eslint-disable no-console */\n/*\n * console.js: Transport for outputting to the console.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst os = require('os');\nconst { LEVEL, MESSAGE } = require('triple-beam');\nconst TransportStream = require('winston-transport');\n\n/**\n * Transport for outputting to the console.\n * @type {Console}\n * @extends {TransportStream}\n */\nmodule.exports = class Console extends TransportStream {\n  /**\n   * Constructor function for the Console transport object responsible for\n   * persisting log messages and metadata to a terminal or TTY.\n   * @param {!Object} [options={}] - Options for this instance.\n   */\n  constructor(options = {}) {\n    super(options);\n\n    // Expose the name of this Transport on the prototype\n    this.name = options.name || 'console';\n    this.stderrLevels = this._stringArrayToSet(options.stderrLevels);\n    this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels);\n    this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;\n    this.forceConsole = options.forceConsole || false;\n\n    // Keep a reference to the log, warn, and error console methods\n    // in case they get redirected to this transport after the logger is\n    // instantiated. This prevents a circular reference issue.\n    this._consoleLog = console.log.bind(console);\n    this._consoleWarn = console.warn.bind(console);\n    this._consoleError = console.error.bind(console);\n\n    this.setMaxListeners(30);\n  }\n\n  /**\n   * Core logging method exposed to Winston.\n   * @param {Object} info - TODO: add param description.\n   * @param {Function} callback - TODO: add param description.\n   * @returns {undefined}\n   */\n  log(info, callback) {\n    setImmediate(() => this.emit('logged', info));\n\n    // Remark: what if there is no raw...?\n    if (this.stderrLevels[info[LEVEL]]) {\n      if (console._stderr && !this.forceConsole) {\n        // Node.js maps `process.stderr` to `console._stderr`.\n        console._stderr.write(`${info[MESSAGE]}${this.eol}`);\n      } else {\n        // console.error adds a newline\n        this._consoleError(info[MESSAGE]);\n      }\n\n      if (callback) {\n        callback(); // eslint-disable-line callback-return\n      }\n      return;\n    } else if (this.consoleWarnLevels[info[LEVEL]]) {\n      if (console._stderr && !this.forceConsole) {\n        // Node.js maps `process.stderr` to `console._stderr`.\n        // in Node.js console.warn is an alias for console.error\n        console._stderr.write(`${info[MESSAGE]}${this.eol}`);\n      } else {\n        // console.warn adds a newline\n        this._consoleWarn(info[MESSAGE]);\n      }\n\n      if (callback) {\n        callback(); // eslint-disable-line callback-return\n      }\n      return;\n    }\n\n    if (console._stdout && !this.forceConsole) {\n      // Node.js maps `process.stdout` to `console._stdout`.\n      console._stdout.write(`${info[MESSAGE]}${this.eol}`);\n    } else {\n      // console.log adds a newline.\n      this._consoleLog(info[MESSAGE]);\n    }\n\n    if (callback) {\n      callback(); // eslint-disable-line callback-return\n    }\n  }\n\n  /**\n   * Returns a Set-like object with strArray's elements as keys (each with the\n   * value true).\n   * @param {Array} strArray - Array of Set-elements as strings.\n   * @param {?string} [errMsg] - Custom error message thrown on invalid input.\n   * @returns {Object} - TODO: add return description.\n   * @private\n   */\n  _stringArrayToSet(strArray, errMsg) {\n    if (!strArray) return {};\n\n    errMsg =\n      errMsg || 'Cannot make set from type other than Array of string elements';\n\n    if (!Array.isArray(strArray)) {\n      throw new Error(errMsg);\n    }\n\n    return strArray.reduce((set, el) => {\n      if (typeof el !== 'string') {\n        throw new Error(errMsg);\n      }\n      set[el] = true;\n\n      return set;\n    }, {});\n  }\n};\n"
  },
  {
    "path": "lib/winston/transports/file.js",
    "content": "/* eslint-disable complexity,max-statements */\n/**\n * file.js: Transport for outputting to a local log file.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst asyncSeries = require('async/series');\nconst zlib = require('zlib');\nconst { MESSAGE } = require('triple-beam');\nconst { Stream, PassThrough } = require('readable-stream');\nconst TransportStream = require('winston-transport');\nconst debug = require('@dabh/diagnostics')('winston:file');\nconst os = require('os');\nconst tailFile = require('../tail-file');\n\n/**\n * Transport for outputting to a local log file.\n * @type {File}\n * @extends {TransportStream}\n */\nmodule.exports = class File extends TransportStream {\n  /**\n   * Constructor function for the File transport object responsible for\n   * persisting log messages and metadata to one or more files.\n   * @param {Object} options - Options for this instance.\n   */\n  constructor(options = {}) {\n    super(options);\n\n    // Expose the name of this Transport on the prototype.\n    this.name = options.name || 'file';\n\n    // Helper function which throws an `Error` in the event that any of the\n    // rest of the arguments is present in `options`.\n    function throwIf(target, ...args) {\n      args.slice(1).forEach(name => {\n        if (options[name]) {\n          throw new Error(`Cannot set ${name} and ${target} together`);\n        }\n      });\n    }\n\n    // Setup the base stream that always gets piped to to handle buffering.\n    this._stream = new PassThrough();\n    this._stream.setMaxListeners(30);\n\n    // Bind this context for listener methods.\n    this._onError = this._onError.bind(this);\n\n    if (options.filename || options.dirname) {\n      throwIf('filename or dirname', 'stream');\n      this._basename = this.filename = options.filename\n        ? path.basename(options.filename)\n        : 'winston.log';\n\n      this.dirname = options.dirname || path.dirname(options.filename);\n      this.options = options.options || { flags: 'a' };\n    } else if (options.stream) {\n      // eslint-disable-next-line no-console\n      console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');\n      throwIf('stream', 'filename', 'maxsize');\n      this._dest = this._stream.pipe(this._setupStream(options.stream));\n      this.dirname = path.dirname(this._dest.path);\n      // We need to listen for drain events when write() returns false. This\n      // can make node mad at times.\n    } else {\n      throw new Error('Cannot log to file without filename or stream.');\n    }\n\n    this.maxsize = options.maxsize || null;\n    this.rotationFormat = options.rotationFormat || false;\n    this.zippedArchive = options.zippedArchive || false;\n    this.maxFiles = options.maxFiles || null;\n    this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL;\n    this.tailable = options.tailable || false;\n    this.lazy = options.lazy || false;\n\n    // Internal state variables representing the number of files this instance\n    // has created and the current size (in bytes) of the current logfile.\n    this._size = 0;\n    this._pendingSize = 0;\n    this._created = 0;\n    this._drain = false;\n    this._opening = false;\n    this._ending = false;\n    this._fileExist = false;\n\n    if (this.dirname) this._createLogDirIfNotExist(this.dirname);\n    if (!this.lazy) this.open();\n  }\n\n  finishIfEnding() {\n    if (this._ending) {\n      if (this._opening) {\n        this.once('open', () => {\n          this._stream.once('finish', () => this.emit('finish'));\n          setImmediate(() => this._stream.end());\n        });\n      } else {\n        this._stream.once('finish', () => this.emit('finish'));\n        setImmediate(() => this._stream.end());\n      }\n    }\n  }\n\n  /**\n   * Called by Node.js Writable stream before emitting 'finish'.\n   * Ensures all buffered data is flushed to the underlying file stream\n   * before the transport signals completion.\n   * @param {Function} callback - Callback to signal completion.\n   * @private\n   */\n  _final(callback) {\n    // If still opening, wait for the file to be opened first\n    if (this._opening) {\n      this.once('open', () => this._final(callback));\n      return;\n    }\n\n    // End the PassThrough stream\n    this._stream.end();\n\n    // No destination stream, call callback immediately\n    if (!this._dest) {\n      return callback();\n    }\n\n    // Destination is already finished\n    if (this._dest.writableFinished) {\n      return callback();\n    }\n\n    // Wait for destination stream to finish writing\n    this._dest.once('finish', callback);\n    this._dest.once('error', callback);\n  }\n\n  /**\n   * Core logging method exposed to Winston. Metadata is optional.\n   * @param {Object} info - TODO: add param description.\n   * @param {Function} callback - TODO: add param description.\n   * @returns {undefined}\n   */\n  log(info, callback = () => { }) {\n    // Remark: (jcrugzz) What is necessary about this callback(null, true) now\n    // when thinking about 3.x? Should silent be handled in the base\n    // TransportStream _write method?\n    if (this.silent) {\n      callback();\n      return true;\n    }\n\n\n    // Output stream buffer is full and has asked us to wait for the drain event\n    if (this._drain) {\n      this._stream.once('drain', () => {\n        this._drain = false;\n        this.log(info, callback);\n      });\n      return;\n    }\n    if (this._rotate) {\n      this._stream.once('rotate', () => {\n        this._rotate = false;\n        this.log(info, callback);\n      });\n      return;\n    }\n    if (this.lazy) {\n      if (!this._fileExist) {\n        if (!this._opening) {\n          this.open();\n        }\n        this.once('open', () => {\n          this._fileExist = true;\n          this.log(info, callback);\n          return;\n        });\n        return;\n      }\n      if (this._needsNewFile(this._pendingSize)) {\n        this._dest.once('close', () => {\n          if (!this._opening) {\n            this.open();\n          }\n          this.once('open', () => {\n            this.log(info, callback);\n            return;\n          });\n          return;\n        });\n        return;\n      }\n    }\n\n    // Grab the raw string and append the expected EOL.\n    const output = `${info[MESSAGE]}${this.eol}`;\n    const bytes = Buffer.byteLength(output);\n\n    // After we have written to the PassThrough check to see if we need\n    // to rotate to the next file.\n    //\n    // Remark: This gets called too early and does not depict when data\n    // has been actually flushed to disk.\n    function logged() {\n      this._size += bytes;\n      this._pendingSize -= bytes;\n\n      debug('logged %s %s', this._size, output);\n      this.emit('logged', info);\n\n      // Do not attempt to rotate files while rotating\n      if (this._rotate) {\n        return;\n      }\n\n      // Do not attempt to rotate files while opening\n      if (this._opening) {\n        return;\n      }\n\n      // Check to see if we need to end the stream and create a new one.\n      if (!this._needsNewFile()) {\n        return;\n      }\n      if (this.lazy) {\n        this._endStream(() => {this.emit('fileclosed');});\n        return;\n      }\n\n      // End the current stream, ensure it flushes and create a new one.\n      // This could potentially be optimized to not run a stat call but its\n      // the safest way since we are supporting `maxFiles`.\n      this._rotate = true;\n      this._endStream(() => this._rotateFile());\n    }\n\n    // Keep track of the pending bytes being written while files are opening\n    // in order to properly rotate the PassThrough this._stream when the file\n    // eventually does open.\n    this._pendingSize += bytes;\n    if (this._opening\n      && !this.rotatedWhileOpening\n      && this._needsNewFile(this._size + this._pendingSize)) {\n      this.rotatedWhileOpening = true;\n    }\n\n    const written = this._stream.write(output, logged.bind(this));\n    if (!written) {\n      this._drain = true;\n      this._stream.once('drain', () => {\n        this._drain = false;\n        callback();\n      });\n    } else {\n      callback(); // eslint-disable-line callback-return\n    }\n\n    debug('written', written, this._drain);\n\n    this.finishIfEnding();\n\n    return written;\n  }\n\n  /**\n   * Query the transport. Options object is optional.\n   * @param {Object} options - Loggly-like query options for this instance.\n   * @param {function} callback - Continuation to respond to when complete.\n   * TODO: Refactor me.\n   */\n  query(options, callback) {\n    if (typeof options === 'function') {\n      callback = options;\n      options = {};\n    }\n\n    options = normalizeQuery(options);\n    const file = path.join(this.dirname, this.filename);\n    let buff = '';\n    let results = [];\n    let row = 0;\n\n    const stream = fs.createReadStream(file, {\n      encoding: 'utf8'\n    });\n\n    stream.on('error', err => {\n      if (stream.readable) {\n        stream.destroy();\n      }\n      if (!callback) {\n        return;\n      }\n\n      return err.code !== 'ENOENT' ? callback(err) : callback(null, results);\n    });\n\n    stream.on('data', data => {\n      data = (buff + data).split(/\\n+/);\n      const l = data.length - 1;\n      let i = 0;\n\n      for (; i < l; i++) {\n        if (!options.start || row >= options.start) {\n          add(data[i]);\n        }\n        row++;\n      }\n\n      buff = data[l];\n    });\n\n    stream.on('close', () => {\n      if (buff) {\n        add(buff, true);\n      }\n      if (options.order === 'desc') {\n        results = results.reverse();\n      }\n\n      // eslint-disable-next-line callback-return\n      if (callback) callback(null, results);\n    });\n\n    function add(buff, attempt) {\n      try {\n        const log = JSON.parse(buff);\n        if (check(log)) {\n          push(log);\n        }\n      } catch (e) {\n        if (!attempt) {\n          stream.emit('error', e);\n        }\n      }\n    }\n\n    function push(log) {\n      if (\n        options.rows &&\n        results.length >= options.rows &&\n        options.order !== 'desc'\n      ) {\n        if (stream.readable) {\n          stream.destroy();\n        }\n        return;\n      }\n\n      if (options.fields) {\n        log = options.fields.reduce((obj, key) => {\n          obj[key] = log[key];\n          return obj;\n        }, {});\n      }\n\n      if (options.order === 'desc') {\n        if (results.length >= options.rows) {\n          results.shift();\n        }\n      }\n      results.push(log);\n    }\n\n    function check(log) {\n      if (!log) {\n        return;\n      }\n\n      if (typeof log !== 'object') {\n        return;\n      }\n\n      const time = new Date(log.timestamp);\n      if (\n        (options.from && time < options.from) ||\n        (options.until && time > options.until) ||\n        (options.level && options.level !== log.level)\n      ) {\n        return;\n      }\n\n      return true;\n    }\n\n    function normalizeQuery(options) {\n      options = options || {};\n\n      // limit\n      options.rows = options.rows || options.limit || 10;\n\n      // starting row offset\n      options.start = options.start || 0;\n\n      // now\n      options.until = options.until || new Date();\n      if (typeof options.until !== 'object') {\n        options.until = new Date(options.until);\n      }\n\n      // now - 24\n      options.from = options.from || (options.until - (24 * 60 * 60 * 1000));\n      if (typeof options.from !== 'object') {\n        options.from = new Date(options.from);\n      }\n\n      // 'asc' or 'desc'\n      options.order = options.order || 'desc';\n\n      return options;\n    }\n  }\n\n  /**\n   * Returns a log stream for this transport. Options object is optional.\n   * @param {Object} options - Stream options for this instance.\n   * @returns {Stream} - TODO: add return description.\n   * TODO: Refactor me.\n   */\n  stream(options = {}) {\n    const file = path.join(this.dirname, this.filename);\n    const stream = new Stream();\n    const tail = {\n      file,\n      start: options.start\n    };\n\n    stream.destroy = tailFile(tail, (err, line) => {\n      if (err) {\n        return stream.emit('error', err);\n      }\n\n      try {\n        stream.emit('data', line);\n        line = JSON.parse(line);\n        stream.emit('log', line);\n      } catch (e) {\n        stream.emit('error', e);\n      }\n    });\n\n    return stream;\n  }\n\n  /**\n   * Checks to see the filesize of.\n   * @returns {undefined}\n   */\n  open() {\n    // If we do not have a filename then we were passed a stream and\n    // don't need to keep track of size.\n    if (!this.filename) return;\n    if (this._opening) return;\n\n    this._opening = true;\n\n    // Stat the target file to get the size and create the stream.\n    this.stat((err, size) => {\n      if (err) {\n        return this.emit('error', err);\n      }\n      debug('stat done: %s { size: %s }', this.filename, size);\n      this._size = size;\n      this._dest = this._createStream(this._stream);\n      this._opening = false;\n      this.once('open', () => {\n        if (!this._stream.emit('rotate')) {\n          this._rotate = false;\n        }\n      });\n    });\n  }\n\n  /**\n   * Stat the file and assess information in order to create the proper stream.\n   * @param {function} callback - TODO: add param description.\n   * @returns {undefined}\n   */\n  stat(callback) {\n    const target = this._getFile();\n    const fullpath = path.join(this.dirname, target);\n\n    fs.stat(fullpath, (err, stat) => {\n      if (err && err.code === 'ENOENT') {\n        debug('ENOENT ok', fullpath);\n        // Update internally tracked filename with the new target name.\n        this.filename = target;\n        return callback(null, 0);\n      }\n\n      if (err) {\n        debug(`err ${err.code} ${fullpath}`);\n        return callback(err);\n      }\n\n      if (!stat || this._needsNewFile(stat.size)) {\n        // If `stats.size` is greater than the `maxsize` for this\n        // instance then try again.\n        return this._incFile(() => this.stat(callback));\n      }\n\n      // Once we have figured out what the filename is, set it\n      // and return the size.\n      this.filename = target;\n      callback(null, stat.size);\n    });\n  }\n\n  /**\n   * Closes the stream associated with this instance.\n   * @param {function} cb - TODO: add param description.\n   * @returns {undefined}\n   */\n  close(cb) {\n    if (!this._stream) {\n      return;\n    }\n\n    this._stream.end(() => {\n      if (cb) {\n        cb(); // eslint-disable-line callback-return\n      }\n      this.emit('flush');\n      this.emit('closed');\n    });\n  }\n\n  /**\n   * TODO: add method description.\n   * @param {number} size - TODO: add param description.\n   * @returns {undefined}\n   */\n  _needsNewFile(size) {\n    size = size || this._size;\n    return this.maxsize && size >= this.maxsize;\n  }\n\n  /**\n   * TODO: add method description.\n   * @param {Error} err - TODO: add param description.\n   * @returns {undefined}\n   */\n  _onError(err) {\n    this.emit('error', err);\n  }\n\n  /**\n   * TODO: add method description.\n   * @param {Stream} stream - TODO: add param description.\n   * @returns {mixed} - TODO: add return description.\n   */\n  _setupStream(stream) {\n    stream.on('error', this._onError);\n\n    return stream;\n  }\n\n  /**\n   * TODO: add method description.\n   * @param {Stream} stream - TODO: add param description.\n   * @returns {mixed} - TODO: add return description.\n   */\n  _cleanupStream(stream) {\n    stream.removeListener('error', this._onError);\n    stream.destroy();\n    return stream;\n  }\n\n  /**\n   * TODO: add method description.\n   */\n  _rotateFile() {\n    this._incFile(() => this.open());\n  }\n\n  /**\n   * Unpipe from the stream that has been marked as full and end it so it\n   * flushes to disk.\n   *\n   * @param {function} callback - Callback for when the current file has closed.\n   * @private\n   */\n  _endStream(callback = () => { }) {\n    if (this._dest) {\n      this._stream.unpipe(this._dest);\n      this._dest.end(() => {\n        this._cleanupStream(this._dest);\n        callback();\n      });\n    } else {\n      callback(); // eslint-disable-line callback-return\n    }\n  }\n\n  /**\n   * Returns the WritableStream for the active file on this instance. If we\n   * should gzip the file then a zlib stream is returned.\n   *\n   * @param {ReadableStream} source –PassThrough to pipe to the file when open.\n   * @returns {WritableStream} Stream that writes to disk for the active file.\n   */\n  _createStream(source) {\n    const fullpath = path.join(this.dirname, this.filename);\n\n    debug('create stream start', fullpath, this.options);\n    const dest = fs.createWriteStream(fullpath, this.options)\n      // TODO: What should we do with errors here?\n      .on('error', err => debug(err))\n      .on('close', () => debug('close', dest.path, dest.bytesWritten))\n      .on('open', () => {\n        debug('file open ok', fullpath);\n        this.emit('open', fullpath);\n        source.pipe(dest);\n\n        // If rotation occured during the open operation then we immediately\n        // start writing to a new PassThrough, begin opening the next file\n        // and cleanup the previous source and dest once the source has drained.\n        if (this.rotatedWhileOpening) {\n          this._stream = new PassThrough();\n          this._stream.setMaxListeners(30);\n          this._rotateFile();\n          this.rotatedWhileOpening = false;\n          this._cleanupStream(dest);\n          source.end();\n        }\n      });\n\n    debug('create stream ok', fullpath);\n    return dest;\n  }\n\n  /**\n   * TODO: add method description.\n   * @param {function} callback - TODO: add param description.\n   * @returns {undefined}\n   */\n  _incFile(callback) {\n    debug('_incFile', this.filename);\n    const ext = path.extname(this._basename);\n    const basename = path.basename(this._basename, ext);\n    const tasks = [];\n\n    if (this.zippedArchive) {\n      tasks.push(\n        function (cb) {\n          const num = this._created > 0 && !this.tailable ? this._created : '';\n          this._compressFile(\n            path.join(this.dirname, `${basename}${num}${ext}`),\n            path.join(this.dirname, `${basename}${num}${ext}.gz`),\n            cb\n          );\n        }.bind(this)\n      );\n    }\n\n    tasks.push(\n      function (cb) {\n        if (!this.tailable) {\n          this._created += 1;\n          this._checkMaxFilesIncrementing(ext, basename, cb);\n        } else {\n          this._checkMaxFilesTailable(ext, basename, cb);\n        }\n      }.bind(this)\n    );\n\n    asyncSeries(tasks, callback);\n  }\n\n  /**\n   * Gets the next filename to use for this instance in the case that log\n   * filesizes are being capped.\n   * @returns {string} - TODO: add return description.\n   * @private\n   */\n  _getFile() {\n    const ext = path.extname(this._basename);\n    const basename = path.basename(this._basename, ext);\n    const isRotation = this.rotationFormat\n      ? this.rotationFormat()\n      : this._created;\n\n    // Caveat emptor (indexzero): rotationFormat() was broken by design When\n    // combined with max files because the set of files to unlink is never\n    // stored.\n    return !this.tailable && this._created\n      ? `${basename}${isRotation}${ext}`\n      : `${basename}${ext}`;\n  }\n\n  /**\n   * Increment the number of files created or checked by this instance.\n   * @param {mixed} ext - TODO: add param description.\n   * @param {mixed} basename - TODO: add param description.\n   * @param {mixed} callback - TODO: add param description.\n   * @returns {undefined}\n   * @private\n   */\n  _checkMaxFilesIncrementing(ext, basename, callback) {\n    // Check for maxFiles option and delete file.\n    if (!this.maxFiles || this._created < this.maxFiles) {\n      return setImmediate(callback);\n    }\n\n    const oldest = this._created - this.maxFiles;\n    const isOldest = oldest !== 0 ? oldest : '';\n    const isZipped = this.zippedArchive ? '.gz' : '';\n    const filePath = `${basename}${isOldest}${ext}${isZipped}`;\n    const target = path.join(this.dirname, filePath);\n\n    fs.unlink(target, callback);\n  }\n\n  /**\n   * Roll files forward based on integer, up to maxFiles. e.g. if base if\n   * file.log and it becomes oversized, roll to file1.log, and allow file.log\n   * to be re-used. If file is oversized again, roll file1.log to file2.log,\n   * roll file.log to file1.log, and so on.\n   * @param {mixed} ext - TODO: add param description.\n   * @param {mixed} basename - TODO: add param description.\n   * @param {mixed} callback - TODO: add param description.\n   * @returns {undefined}\n   * @private\n   */\n  _checkMaxFilesTailable(ext, basename, callback) {\n    const tasks = [];\n    if (!this.maxFiles) {\n      return;\n    }\n\n    // const isZipped = this.zippedArchive ? '.gz' : '';\n    const isZipped = this.zippedArchive ? '.gz' : '';\n    for (let x = this.maxFiles - 1; x > 1; x--) {\n      tasks.push(function (i, cb) {\n        let fileName = `${basename}${(i - 1)}${ext}${isZipped}`;\n        const tmppath = path.join(this.dirname, fileName);\n\n        fs.exists(tmppath, exists => {\n          if (!exists) {\n            return cb(null);\n          }\n\n          fileName = `${basename}${i}${ext}${isZipped}`;\n          fs.rename(tmppath, path.join(this.dirname, fileName), cb);\n        });\n      }.bind(this, x));\n    }\n\n    asyncSeries(tasks, () => {\n      fs.rename(\n        path.join(this.dirname, `${basename}${ext}${isZipped}`),\n        path.join(this.dirname, `${basename}1${ext}${isZipped}`),\n        callback\n      );\n    });\n  }\n\n  /**\n   * Compresses src to dest with gzip and unlinks src\n   * @param {string} src - path to source file.\n   * @param {string} dest - path to zipped destination file.\n   * @param {Function} callback - callback called after file has been compressed.\n   * @returns {undefined}\n   * @private\n   */\n  _compressFile(src, dest, callback) {\n    fs.access(src, fs.F_OK, (err) => {\n      if (err) {\n        return callback();\n      }\n      var gzip = zlib.createGzip();\n      var inp = fs.createReadStream(src);\n      var out = fs.createWriteStream(dest);\n      out.on('finish', () => {\n        fs.unlink(src, callback);\n      });\n      inp.pipe(gzip).pipe(out);\n    });\n  }\n\n  _createLogDirIfNotExist(dirPath) {\n    /* eslint-disable no-sync */\n    if (!fs.existsSync(dirPath)) {\n      fs.mkdirSync(dirPath, { recursive: true });\n    }\n    /* eslint-enable no-sync */\n  }\n};\n"
  },
  {
    "path": "lib/winston/transports/http.js",
    "content": "/**\n * http.js: Transport for outputting to a json-rpcserver.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst http = require('http');\nconst https = require('https');\nconst { Stream } = require('readable-stream');\nconst TransportStream = require('winston-transport');\nconst { configure } = require('safe-stable-stringify');\n\n/**\n * Transport for outputting to a json-rpc server.\n * @type {Stream}\n * @extends {TransportStream}\n */\nmodule.exports = class Http extends TransportStream {\n  /**\n   * Constructor function for the Http transport object responsible for\n   * persisting log messages and metadata to a terminal or TTY.\n   * @param {!Object} [options={}] - Options for this instance.\n   */\n  // eslint-disable-next-line max-statements\n  constructor(options = {}) {\n    super(options);\n\n    this.options = options;\n    this.name = options.name || 'http';\n    this.ssl = !!options.ssl;\n    this.host = options.host || 'localhost';\n    this.port = options.port;\n    this.auth = options.auth;\n    this.path = options.path || '';\n    this.maximumDepth = options.maximumDepth;\n    this.agent = options.agent;\n    this.headers = options.headers || {};\n    this.headers['content-type'] = 'application/json';\n    this.batch = options.batch || false;\n    this.batchInterval = options.batchInterval || 5000;\n    this.batchCount = options.batchCount || 10;\n    this.batchOptions = [];\n    this.batchTimeoutID = -1;\n    this.batchCallback = {};\n\n    if (!this.port) {\n      this.port = this.ssl ? 443 : 80;\n    }\n  }\n\n  /**\n   * Core logging method exposed to Winston.\n   * @param {Object} info - TODO: add param description.\n   * @param {function} callback - TODO: add param description.\n   * @returns {undefined}\n   */\n  log(info, callback) {\n    this._request(info, null, null, (err, res) => {\n      if (res && res.statusCode !== 200) {\n        err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);\n      }\n\n      if (err) {\n        this.emit('warn', err);\n      } else {\n        this.emit('logged', info);\n      }\n    });\n\n    // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering\n    // and block more requests from happening?\n    if (callback) {\n      setImmediate(callback);\n    }\n  }\n\n  /**\n   * Query the transport. Options object is optional.\n   * @param {Object} options -  Loggly-like query options for this instance.\n   * @param {function} callback - Continuation to respond to when complete.\n   * @returns {undefined}\n   */\n  query(options, callback) {\n    if (typeof options === 'function') {\n      callback = options;\n      options = {};\n    }\n\n    options = {\n      method: 'query',\n      params: this.normalizeQuery(options)\n    };\n\n    const auth = options.params.auth || null;\n    delete options.params.auth;\n\n    const path = options.params.path || null;\n    delete options.params.path;\n\n    this._request(options, auth, path, (err, res, body) => {\n      if (res && res.statusCode !== 200) {\n        err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);\n      }\n\n      if (err) {\n        return callback(err);\n      }\n\n      if (typeof body === 'string') {\n        try {\n          body = JSON.parse(body);\n        } catch (e) {\n          return callback(e);\n        }\n      }\n\n      callback(null, body);\n    });\n  }\n\n  /**\n   * Returns a log stream for this transport. Options object is optional.\n   * @param {Object} options - Stream options for this instance.\n   * @returns {Stream} - TODO: add return description\n   */\n  stream(options = {}) {\n    const stream = new Stream();\n    options = {\n      method: 'stream',\n      params: options\n    };\n\n    const path = options.params.path || null;\n    delete options.params.path;\n\n    const auth = options.params.auth || null;\n    delete options.params.auth;\n\n    let buff = '';\n    const req = this._request(options, auth, path);\n\n    stream.destroy = () => req.destroy();\n    req.on('data', data => {\n      data = (buff + data).split(/\\n+/);\n      const l = data.length - 1;\n\n      let i = 0;\n      for (; i < l; i++) {\n        try {\n          stream.emit('log', JSON.parse(data[i]));\n        } catch (e) {\n          stream.emit('error', e);\n        }\n      }\n\n      buff = data[l];\n    });\n    req.on('error', err => stream.emit('error', err));\n\n    return stream;\n  }\n\n  /**\n   * Make a request to a winstond server or any http server which can\n   * handle json-rpc.\n   * @param {function} options - Options to sent the request.\n   * @param {Object?} auth - authentication options\n   * @param {string} path - request path\n   * @param {function} callback - Continuation to respond to when complete.\n   */\n  _request(options, auth, path, callback) {\n    options = options || {};\n\n    auth = auth || this.auth;\n    path = path || this.path || '';\n\n    if (this.batch) {\n      this._doBatch(options, callback, auth, path);\n    } else {\n      this._doRequest(options, callback, auth, path);\n    }\n  }\n\n  /**\n   * Send or memorize the options according to batch configuration\n   * @param {function} options - Options to sent the request.\n   * @param {function} callback - Continuation to respond to when complete.\n   * @param {Object?} auth - authentication options\n   * @param {string} path - request path\n   */\n  _doBatch(options, callback, auth, path) {\n    this.batchOptions.push(options);\n    if (this.batchOptions.length === 1) {\n      // First message stored, it's time to start the timeout!\n      const me = this;\n      this.batchCallback = callback;\n      this.batchTimeoutID = setTimeout(function () {\n        // timeout is reached, send all messages to endpoint\n        me.batchTimeoutID = -1;\n        me._doBatchRequest(me.batchCallback, auth, path);\n      }, this.batchInterval);\n    }\n    if (this.batchOptions.length === this.batchCount) {\n      // max batch count is reached, send all messages to endpoint\n      this._doBatchRequest(this.batchCallback, auth, path);\n    }\n  }\n\n  /**\n   * Initiate a request with the memorized batch options, stop the batch timeout\n   * @param {function} callback - Continuation to respond to when complete.\n   * @param {Object?} auth - authentication options\n   * @param {string} path - request path\n   */\n  _doBatchRequest(callback, auth, path) {\n    if (this.batchTimeoutID > 0) {\n      clearTimeout(this.batchTimeoutID);\n      this.batchTimeoutID = -1;\n    }\n    const batchOptionsCopy = this.batchOptions.slice();\n    this.batchOptions = [];\n    this._doRequest(batchOptionsCopy, callback, auth, path);\n  }\n\n  /**\n   * Make a request to a winstond server or any http server which can\n   * handle json-rpc.\n   * @param {function} options - Options to sent the request.\n   * @param {function} callback - Continuation to respond to when complete.\n   * @param {Object?} auth - authentication options\n   * @param {string} path - request path\n   */\n  _doRequest(options, callback, auth, path) {\n    // Prepare options for outgoing HTTP request\n    const headers = Object.assign({}, this.headers);\n    if (auth && auth.bearer) {\n      headers.Authorization = `Bearer ${auth.bearer}`;\n    }\n    const req = (this.ssl ? https : http).request({\n      ...this.options,\n      method: 'POST',\n      host: this.host,\n      port: this.port,\n      path: `/${path.replace(/^\\//, '')}`,\n      headers: headers,\n      auth: (auth && auth.username && auth.password) ? (`${auth.username}:${auth.password}`) : '',\n      agent: this.agent\n    });\n\n    req.on('error', callback);\n    req.on('response', res => (\n      res.on('end', () => callback(null, res)).resume()\n    ));\n    const jsonStringify = configure({\n      ...(this.maximumDepth && { maximumDepth: this.maximumDepth })\n    });\n    req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8'));\n  }\n};\n"
  },
  {
    "path": "lib/winston/transports/index.d.ts",
    "content": "// Type definitions for winston 3.0\n// Project: https://github.com/winstonjs/winston\n\n/// <reference types=\"node\" />\n\nimport { Agent } from 'http';\n\nimport * as Transport from 'winston-transport';\n\ndeclare namespace winston {\n  interface ConsoleTransportOptions extends Transport.TransportStreamOptions {\n    consoleWarnLevels?: string[];\n    stderrLevels?: string[];\n    debugStdout?: boolean;\n    eol?: string;\n    forceConsole?: boolean;\n  }\n\n  interface ConsoleTransportInstance extends Transport {\n    name: string;\n    stderrLevels: string[];\n    eol: string;\n\n    new (options?: ConsoleTransportOptions): ConsoleTransportInstance;\n  }\n\n  interface FileTransportOptions extends Transport.TransportStreamOptions {\n    filename?: string;\n    dirname?: string;\n    options?: object;\n    maxsize?: number;\n    stream?: NodeJS.WritableStream;\n    rotationFormat?: Function;\n    zippedArchive?: boolean;\n    maxFiles?: number;\n    eol?: string;\n    tailable?: boolean;\n    lazy?: boolean;\n  }\n\n  interface FileTransportInstance extends Transport {\n    name: string;\n    filename: string;\n    dirname: string;\n    options: object;\n    maxsize: number | null;\n    rotationFormat: Function | boolean;\n    zippedArchive: boolean;\n    maxFiles: number | null;\n    eol: string;\n    tailable: boolean;\n    lazy: boolean;\n\n    new (options?: FileTransportOptions): FileTransportInstance;\n  }\n\n  interface HttpTransportOptions extends Transport.TransportStreamOptions {\n    ssl?: any;\n    host?: string;\n    port?: number;\n    auth?: {\n      username?: string | undefined;\n      password?: string | undefined;\n      bearer?: string | undefined;\n    };\n    path?: string;\n    agent?: Agent;\n    headers?: object;\n    batch?: boolean;\n    batchInterval?: number;\n    batchCount?: number;\n    replacer?: (key: string, value: any) => any;\n    maximumDepth?: number;\n  }\n\n  interface HttpTransportInstance extends Transport {\n    name: string;\n    ssl: boolean;\n    host: string;\n    maximumDepth: number;\n    port: number;\n    auth?: {\n      username?: string | undefined;\n      password?: string | undefined;\n      bearer?: string | undefined;\n    };\n    path: string;\n    agent?: Agent | null;\n\n    new (options?: HttpTransportOptions): HttpTransportInstance;\n  }\n\n  interface StreamTransportOptions extends Transport.TransportStreamOptions {\n    stream: NodeJS.WritableStream;\n    eol?: string;\n  }\n\n  interface StreamTransportInstance extends Transport {\n    eol: string;\n\n    new (options?: StreamTransportOptions): StreamTransportInstance;\n  }\n\n  interface Transports {\n    FileTransportOptions: FileTransportOptions;\n    File: FileTransportInstance;\n    ConsoleTransportOptions: ConsoleTransportOptions;\n    Console: ConsoleTransportInstance;\n    HttpTransportOptions: HttpTransportOptions;\n    Http: HttpTransportInstance;\n    StreamTransportOptions: StreamTransportOptions;\n    Stream: StreamTransportInstance;\n  }\n}\n\ndeclare const winston: winston.Transports;\nexport = winston;\n"
  },
  {
    "path": "lib/winston/transports/index.js",
    "content": "/**\n * transports.js: Set of all transports Winston knows about.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\n/**\n * TODO: add property description.\n * @type {Console}\n */\nObject.defineProperty(exports, 'Console', {\n  configurable: true,\n  enumerable: true,\n  get() {\n    return require('./console');\n  }\n});\n\n/**\n * TODO: add property description.\n * @type {File}\n */\nObject.defineProperty(exports, 'File', {\n  configurable: true,\n  enumerable: true,\n  get() {\n    return require('./file');\n  }\n});\n\n/**\n * TODO: add property description.\n * @type {Http}\n */\nObject.defineProperty(exports, 'Http', {\n  configurable: true,\n  enumerable: true,\n  get() {\n    return require('./http');\n  }\n});\n\n/**\n * TODO: add property description.\n * @type {Stream}\n */\nObject.defineProperty(exports, 'Stream', {\n  configurable: true,\n  enumerable: true,\n  get() {\n    return require('./stream');\n  }\n});\n"
  },
  {
    "path": "lib/winston/transports/stream.js",
    "content": "/**\n * stream.js: Transport for outputting to any arbitrary stream.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst isStream = require('is-stream');\nconst { MESSAGE } = require('triple-beam');\nconst os = require('os');\nconst TransportStream = require('winston-transport');\n\n/**\n * Transport for outputting to any arbitrary stream.\n * @type {Stream}\n * @extends {TransportStream}\n */\nmodule.exports = class Stream extends TransportStream {\n  /**\n   * Constructor function for the Console transport object responsible for\n   * persisting log messages and metadata to a terminal or TTY.\n   * @param {!Object} [options={}] - Options for this instance.\n   */\n  constructor(options = {}) {\n    super(options);\n\n    if (!options.stream || !isStream(options.stream)) {\n      throw new Error('options.stream is required.');\n    }\n\n    // We need to listen for drain events when write() returns false. This can\n    // make node mad at times.\n    this._stream = options.stream;\n    this._stream.setMaxListeners(Infinity);\n    this.isObjectMode = options.stream._writableState.objectMode;\n    this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL;\n  }\n\n  /**\n   * Core logging method exposed to Winston.\n   * @param {Object} info - TODO: add param description.\n   * @param {Function} callback - TODO: add param description.\n   * @returns {undefined}\n   */\n  log(info, callback) {\n    setImmediate(() => this.emit('logged', info));\n    if (this.isObjectMode) {\n      this._stream.write(info);\n      if (callback) {\n        callback(); // eslint-disable-line callback-return\n      }\n      return;\n    }\n\n    this._stream.write(`${info[MESSAGE]}${this.eol}`);\n    if (callback) {\n      callback(); // eslint-disable-line callback-return\n    }\n    return;\n  }\n};\n"
  },
  {
    "path": "lib/winston.js",
    "content": "/**\n * winston.js: Top-level include defining Winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst logform = require('logform');\nconst { warn } = require('./winston/common');\n\n/**\n * Expose version. Use `require` method for `webpack` support.\n * @type {string}\n */\nexports.version = require('../package.json').version;\n/**\n * Include transports defined by default by winston\n * @type {Array}\n */\nexports.transports = require('./winston/transports');\n/**\n * Expose utility methods\n * @type {Object}\n */\nexports.config = require('./winston/config');\n/**\n * Hoist format-related functionality from logform.\n * @type {Object}\n */\nexports.addColors = logform.levels;\n/**\n * Hoist format-related functionality from logform.\n * @type {Object}\n */\nexports.format = logform.format;\n/**\n * Expose core Logging-related prototypes.\n * @type {function}\n */\nexports.createLogger = require('./winston/create-logger');\n/**\n * Expose core Logging-related prototypes.\n * @type {function}\n */\nexports.Logger = require('./winston/logger');\n/**\n * Expose core Logging-related prototypes.\n * @type {Object}\n */\nexports.ExceptionHandler = require('./winston/exception-handler');\n/**\n * Expose core Logging-related prototypes.\n * @type {Object}\n */\nexports.RejectionHandler = require('./winston/rejection-handler');\n/**\n * Expose core Logging-related prototypes.\n * @type {Container}\n */\nexports.Container = require('./winston/container');\n/**\n * Expose core Logging-related prototypes.\n * @type {Object}\n */\nexports.Transport = require('winston-transport');\n/**\n * We create and expose a default `Container` to `winston.loggers` so that the\n * programmer may manage multiple `winston.Logger` instances without any\n * additional overhead.\n * @example\n *   // some-file1.js\n *   const logger = require('winston').loggers.get('something');\n *\n *   // some-file2.js\n *   const logger = require('winston').loggers.get('something');\n */\nexports.loggers = new exports.Container();\n\n/**\n * We create and expose a 'defaultLogger' so that the programmer may do the\n * following without the need to create an instance of winston.Logger directly:\n * @example\n *   const winston = require('winston');\n *   winston.log('info', 'some message');\n *   winston.error('some error');\n */\nconst defaultLogger = exports.createLogger();\n\n// Pass through the target methods onto `winston.\nObject.keys(exports.config.npm.levels)\n  .concat([\n    'log',\n    'query',\n    'stream',\n    'add',\n    'remove',\n    'clear',\n    'profile',\n    'startTimer',\n    'handleExceptions',\n    'unhandleExceptions',\n    'handleRejections',\n    'unhandleRejections',\n    'configure',\n    'child'\n  ])\n  .forEach(\n    method => (exports[method] = (...args) => defaultLogger[method](...args))\n  );\n\n/**\n * Define getter / setter for the default logger level which need to be exposed\n * by winston.\n * @type {string}\n */\nObject.defineProperty(exports, 'level', {\n  get() {\n    return defaultLogger.level;\n  },\n  set(val) {\n    defaultLogger.level = val;\n  }\n});\n\n/**\n * Define getter for `exceptions` which replaces `handleExceptions` and\n * `unhandleExceptions`.\n * @type {Object}\n */\nObject.defineProperty(exports, 'exceptions', {\n  get() {\n    return defaultLogger.exceptions;\n  }\n});\n\n/**\n * Define getter for `rejections` which replaces `handleRejections` and\n * `unhandleRejections`.\n * @type {Object}\n */\nObject.defineProperty(exports, 'rejections', {\n  get() {\n    return defaultLogger.rejections;\n  }\n});\n\n/**\n * Define getters / setters for appropriate properties of the default logger\n * which need to be exposed by winston.\n * @type {Logger}\n */\n['exitOnError'].forEach(prop => {\n  Object.defineProperty(exports, prop, {\n    get() {\n      return defaultLogger[prop];\n    },\n    set(val) {\n      defaultLogger[prop] = val;\n    }\n  });\n});\n\n/**\n * The default transports and exceptionHandlers for the default winston logger.\n * @type {Object}\n */\nObject.defineProperty(exports, 'default', {\n  get() {\n    return {\n      exceptionHandlers: defaultLogger.exceptionHandlers,\n      rejectionHandlers: defaultLogger.rejectionHandlers,\n      transports: defaultLogger.transports\n    };\n  }\n});\n\n// Have friendlier breakage notices for properties that were exposed by default\n// on winston < 3.0.\nwarn.deprecated(exports, 'setLevels');\nwarn.forFunctions(exports, 'useFormat', ['cli']);\nwarn.forProperties(exports, 'useFormat', ['padLevels', 'stripColors']);\nwarn.forFunctions(exports, 'deprecated', [\n  'addRewriter',\n  'addFilter',\n  'clone',\n  'extend'\n]);\nwarn.forProperties(exports, 'deprecated', ['emitErrs', 'levelLength']);\n\n"
  },
  {
    "path": "package.json",
    "content": "{\n\t\"name\": \"winston\",\n\t\"description\": \"A logger for just about everything.\",\n\t\"version\": \"3.19.0\",\n\t\"author\": \"Charlie Robbins <charlie.robbins@gmail.com>\",\n\t\"maintainers\": [\n\t\t\"David Hyde <dabh@alumni.stanford.edu>\"\n\t],\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/winstonjs/winston.git\"\n\t},\n\t\"keywords\": [\n\t\t\"winston\",\n\t\t\"logger\",\n\t\t\"logging\",\n\t\t\"logs\",\n\t\t\"sysadmin\",\n\t\t\"bunyan\",\n\t\t\"pino\",\n\t\t\"loglevel\",\n\t\t\"tools\",\n\t\t\"json\",\n\t\t\"stream\"\n\t],\n\t\"dependencies\": {\n\t\t\"@dabh/diagnostics\": \"^2.0.8\",\n\t\t\"@colors/colors\": \"^1.6.0\",\n\t\t\"async\": \"^3.2.3\",\n\t\t\"is-stream\": \"^2.0.0\",\n\t\t\"logform\": \"^2.7.0\",\n\t\t\"one-time\": \"^1.0.0\",\n\t\t\"readable-stream\": \"^3.4.0\",\n\t\t\"safe-stable-stringify\": \"^2.3.1\",\n\t\t\"stack-trace\": \"0.0.x\",\n\t\t\"triple-beam\": \"^1.3.0\",\n\t\t\"winston-transport\": \"^4.9.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@babel/cli\": \"^7.23.9\",\n\t\t\"@babel/core\": \"^7.24.0\",\n\t\t\"@babel/preset-env\": \"^7.24.0\",\n\t\t\"@dabh/eslint-config-populist\": \"^4.4.0\",\n\t\t\"@types/node\": \"^20.11.24\",\n\t\t\"abstract-winston-transport\": \"^0.5.1\",\n\t\t\"assume\": \"^2.2.0\",\n\t\t\"cross-spawn-async\": \"^2.2.5\",\n\t\t\"eslint\": \"^8.57.0\",\n\t\t\"hock\": \"^1.4.1\",\n\t\t\"jest\": \"^29.7.0\",\n\t\t\"rimraf\": \"5.0.10\",\n\t\t\"split2\": \"^4.1.0\",\n\t\t\"std-mocks\": \"^2.0.0\",\n\t\t\"through2\": \"^4.0.2\",\n\t\t\"winston-compat\": \"^0.1.5\"\n\t},\n\t\"main\": \"./lib/winston.js\",\n\t\"browser\": \"./dist/winston\",\n\t\"types\": \"./index.d.ts\",\n\t\"scripts\": {\n\t\t\"lint\": \"eslint lib/*.js lib/winston/*.js lib/winston/**/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist\",\n\t\t\"test\": \"jest\",\n\t\t\"test:unit\": \"jest -c test/jest.config.unit.js\",\n\t\t\"test:integration\": \"jest -c test/jest.config.integration.js\",\n\t\t\"test:typescript\": \"npx --package typescript tsc --project test\",\n\t\t\"build\": \"babel lib -d dist\",\n\t\t\"prebuild\": \"rimraf dist\",\n\t\t\"prepublishOnly\": \"npm run build\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">= 12.0.0\"\n\t},\n\t\"license\": \"MIT\"\n}\n"
  },
  {
    "path": "publishing.md",
    "content": "The release process here mostly follows along with the [vbump script](https://github.com/indexzero/vbump) that @indexzero wrote several years ago, but the main steps for a release are as follows:\n\n1. Complete merging in any PRs that should be part of the release.\n2. Update the changelog. Check to make sure you've caught everything using GitHub's compare tool ([example here](https://github.com/winstonjs/winston/compare/v3.6.0...master)).  It's nice to thank the contributors here.  It's nice to organize this by which changes would merit which level of semver bump, and especially call out any breaking changes (major-version-number) concisely at the start.\n3. **Update the version number in package.json and package-lock.json**, bumping as appropriate for [semver](https://semver.org/) based on the most significant position change trigger from the changelog you just wrote/reviewed.  Do not miss this step!\n4. Make sure your local master branch is up to date.\n5. Make sure all the lint checks and tests pass, beyond what the CI might've told you.\n6. On the [Releases tab](https://github.com/winstonjs/winston/releases) in the GitHub UI, click 'Draft a new release' in the upper right corner.\n7. Under the 'Choose a tag' dropdown, type the name of the new version starting with a v (e.g. `v3.7.0`) and don't forget to click the 'Create new tag on publish' option below (this step is annoyingly easy to miss):\n![image](https://user-images.githubusercontent.com/563406/160644343-69325988-4ca2-4329-93da-e08266269506.png)\n8. Paste the same version number, with or without the v (with is probably better) in the release title box.\n9. Paste the contents of the changelog for this release in the 'Describe this release' box.\n10. Click \"Publish release.\"\n11. Back on the command line, `npm publish` and complete npm 2FA as needed.\n12. Update the distribution tags, for example: `npm dist-tag add winston@3.7.0 3.x-latest`.\n13. Verify the distribution tags look correct under the 'Versions' tab at https://www.npmjs.com/package/winston or with `npm dist-tag ls`.\n14. Keep a closer-than-usual eye on issues in the hours and days that follow, prepared to quickly revert/address anything that might be associated with that release.\n\nA more professional version of this would probably use a release branch off master to make sure no other maintainers merge a PR into master between the loading of a compare view for changelog preparation and completion of the process, but we're such a small team that the extra steps are probably not needed. After release, you can also verify with the compare view between the new and prior release tags to see when the latest change was and verify it was before you started the process.\n"
  },
  {
    "path": "test/fixtures/.gitkeep",
    "content": ""
  },
  {
    "path": "test/fixtures/keys/agent2-cert.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV\nUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO\nBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEgMB4GCSqGSIb3DQEJARYR\ncnlAdGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEy\nWjB9MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYD\nVQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEg\nMB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEF\nAANLADBIAkEAyXb8FrRdKbhrKLgLSsn61i1C7w7fVVVd7OQsmV/7p9WB2lWFiDlC\nWKGU9SiIz/A6wNZDUAuc2E+VwtpCT561AQIDAQABMA0GCSqGSIb3DQEBBQUAA0EA\nC8HzpuNhFLCI3A5KkBS5zHAQax6TFUOhbpBCR0aTDbJ6F1liDTK1lmU/BjvPoj+9\n1LHwrmh29rK8kBPEjmymCQ==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "test/fixtures/keys/agent2-key.pem",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5\nQlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH\n9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p\nOHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf\nWRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb\nAFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa\ncgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "test/fixtures/logs/.gitkeep",
    "content": ""
  },
  {
    "path": "test/globalSetup.js",
    "content": "const path = require('path');\nconst { rimraf } = require('rimraf');\n\nfunction cleanTestArtifacts() {\n  console.debug('\\nCleaning test artifacts...');\n  const testArtifacts = path.join(__dirname, 'fixtures', 'logs');\n  rimraf.sync(path.join(testArtifacts, '*log*'), { glob: true });\n}\n\nmodule.exports = async () => {\n  cleanTestArtifacts();\n};\n"
  },
  {
    "path": "test/helpers/handler-tests.js",
    "content": "const assume = require('assume');\n\nconst helpers = require('.');\nconst winston = require('../../lib/winston');\n\nmodule.exports = function ({ helper, listener, name, setup, toggleSetting }) {\n  describe('basics', function () {\n    var handler;\n\n    beforeEach(function () {\n      handler = helpers[helper]();\n    });\n\n    it('has expected methods', function () {\n      assume(handler.handle).is.a('function');\n      assume(handler.unhandle).is.a('function');\n      assume(handler.getAllInfo).is.a('function');\n      assume(handler.getProcessInfo).is.a('function');\n      assume(handler.getOsInfo).is.a('function');\n      assume(handler.getTrace).is.a('function');\n    });\n\n    it(`new ${name}()`, function () {\n      assume(function () {\n        // eslint-disable-next-line no-new\n        new winston[name]();\n      }).throws(/Logger is required/);\n    });\n\n    it(`new ${name}(logger)`, function () {\n      var logger = winston.createLogger();\n      var handler_ = new winston[name](logger);\n      assume(handler_.logger).equals(logger);\n    });\n\n    it('.getProcessInfo()', function () {\n      helpers.assertProcessInfo(handler.getProcessInfo());\n    });\n\n    it('.getOsInfo()', function () {\n      helpers.assertOsInfo(handler.getOsInfo());\n    });\n\n    it('.getTrace(new Error)', function () {\n      helpers.assertTrace(handler.getTrace(new Error()));\n    });\n\n    it('.getTrace()', function () {\n      helpers.assertTrace(handler.getTrace());\n    });\n\n    it('.getAllInfo(undefined)', function () {\n      handler.getAllInfo();\n    });\n  });\n\n  describe('when error case is triggered', function () {\n    beforeEach(function () {\n      this.listeners = helpers[setup]();\n    });\n\n    afterEach(function () {\n      this.listeners.restore();\n    });\n\n    it('.handle()', function (done) {\n      var msg = new Date().toString();\n      var writeable = helpers.writeable(function (info) {\n        assume(info).is.an('object');\n        assume(info.error).is.an('error');\n        assume(info.error.message).equals(msg);\n        assume(info.message).includes(`${listener}: ${msg}`);\n        assume(info.stack).is.a('string');\n        assume(info.process).is.an('object');\n        assume(info.os).is.an('object');\n        assume(info.trace).is.an('array');\n\n        done();\n      });\n\n      var transport = new winston.transports.Stream({ stream: writeable });\n      var handler = helpers[helper]({\n        exitOnError: false,\n        transports: [transport]\n      });\n\n      assume(handler.catcher).is.a('undefined');\n\n      transport[toggleSetting] = true;\n      handler.handle();\n\n      assume(handler.catcher).is.a('function');\n      assume(process.listeners(listener)).deep.equals([\n        handler.catcher\n      ]);\n\n      process.emit(listener, new Error(msg));\n    });\n  });\n};\n"
  },
  {
    "path": "test/helpers/index.js",
    "content": "/*\n * helpers.js: Test helpers for winston\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume'),\n    fs = require('fs'),\n    through = require('through2'),\n    spawn = require('child_process').spawn,\n    stream = require('stream'),\n    winston = require('../../lib/winston'),\n    mockTransport = require('./mocks/mock-transport');\n\nvar helpers = exports;\n\n/**\n * Returns a new winston.Logger instance which will invoke\n * the `write` method on each call to `.log`\n *\n * @param {function} write Write function for the specified stream\n * @returns {Logger} A winston.Logger instance\n */\nhelpers.createLogger = function (write, format) {\n  return winston.createLogger({\n    format,\n    transports: [\n      mockTransport.createMockTransport(write)\n    ]\n  });\n};\n\n/**\n * Returns a new writeable stream with the specified write function.\n * @param {function} write Write function for the specified stream\n * @returns {stream.Writeable} A writeable stream instance\n */\nhelpers.writeable = function (write, objectMode) {\n  return new stream.Writable({\n    objectMode: objectMode !== false,\n    write: write\n  });\n};\n\n/**\n * Creates a new ExceptionHandler instance with a new\n * winston.Logger instance with the specified options\n *\n * @param {Object} opts Options for the logger associated\n *                 with the ExceptionHandler\n * @returns {ExceptionHandler} A new ExceptionHandler instance\n */\nhelpers.exceptionHandler = function (opts) {\n  var logger = winston.createLogger(opts);\n  return new winston.ExceptionHandler(logger);\n};\n\n/**\n * Creates a new RejectionHandler instance with a new\n * winston.Logger instance with the specified options\n *\n * @param {Object} opts Options for the logger associated\n *                 with the RejectionHandler\n * @returns {RejectionHandler} A new ExceptionHandler instance\n */\nhelpers.rejectionHandler = function (opts) {\n  var logger = winston.createLogger(opts);\n  return new winston.RejectionHandler(logger);\n};\n\n/**\n * Removes all listeners to `process.on('uncaughtException')`\n * and returns an object that allows you to restore them later.\n *\n * @returns {Object} Facade to restore uncaughtException handlers.\n */\nhelpers.clearExceptions = function () {\n  var listeners = process.listeners('uncaughtException');\n  process.removeAllListeners('uncaughtException');\n\n  return {\n    restore: function () {\n      process.removeAllListeners('uncaughtException');\n      listeners.forEach(function (fn) {\n        process.on('uncaughtException', fn);\n      });\n    }\n  };\n};\n\n/**\n * Removes all listeners to `process.on('unhandledRejection')`\n * and returns an object that allows you to restore them later.\n *\n * @returns {Object} Facade to restore unhandledRejection handlers.\n */\nhelpers.clearRejections = function () {\n  var listeners = process.listeners('unhandledRejection');\n  process.removeAllListeners('unhandledRejection');\n\n  return {\n    restore: function () {\n      process.removeAllListeners('unhandledRejection');\n      listeners.forEach(function (fn) {\n        process.on('unhandledRejection', fn);\n      });\n    }\n  };\n};\n\n\n/**\n * Attempts to unlink the specifyed `filename` ignoring errors\n * @param {String} File Full path to attempt to unlink.\n */\nhelpers.tryUnlink = function (filename) {\n  try {\n    fs.unlinkSync(filename);\n  } catch (ex) {}\n};\n\n/**\n * Returns a stream that will emit data for the `filename` if it exists\n * and is capable of being opened.\n * @param  {filename} Full path to attempt to read from.\n * @returns {Stream} Stream instance to the contents of the file\n */\nhelpers.tryRead = function tryRead(filename) {\n  var proxy = through();\n  (function inner() {\n    var stream = fs\n      .createReadStream(filename)\n      .once('open', function () {\n        stream.pipe(proxy);\n      })\n      .once('error', function (err) {\n        if (err.code === 'ENOENT') {\n          return setImmediate(inner);\n        }\n        proxy.emit('error', err);\n      });\n  }());\n\n  return proxy;\n};\n\n/**\n * Assumes the process structure associated with an ExceptionHandler\n * for the `obj` provided.\n * @param  {Object} obj Ordinary object to assert against.\n */\nhelpers.assertProcessInfo = function (obj) {\n  assume(obj.pid).is.a('number');\n  // `process.gid` and `process.uid` do no exist on Windows.\n  if (process.platform === 'win32') {\n    assume(obj.uid).is.a('null');\n    assume(obj.gid).is.a('null');\n  } else {\n    assume(obj.uid).is.a('number');\n    assume(obj.gid).is.a('number');\n  }\n  assume(obj.cwd).is.a('string');\n  assume(obj.execPath).is.a('string');\n  assume(obj.version).is.a('string');\n  assume(obj.argv).is.an('array');\n  assume(obj.memoryUsage).is.an('object');\n};\n\n/**\n * Assumes the OS structure associated with an ExceptionHandler\n * for the `obj` provided.\n * @param  {Object} obj Ordinary object to assert against.\n */\nhelpers.assertOsInfo = function (obj) {\n  assume(obj.loadavg).is.an('array');\n  assume(obj.uptime).is.a('number');\n};\n\n/**\n * Assumes the trace structure associated with an ExceptionHandler\n * for the `trace` provided.\n * @param  {Object} trace Ordinary object to assert against.\n */\nhelpers.assertTrace = function (trace) {\n  trace.forEach(function (site) {\n    assume(!site.column || typeof site.column === 'number').true();\n    assume(!site.line || typeof site.line === 'number').true();\n    assume(!site.file || typeof site.file === 'string').true();\n    assume(!site.method || typeof site.method === 'string').true();\n    assume(!site.function || typeof site.function === 'string').true();\n    assume(typeof site.native === 'boolean').true();\n  });\n};\n\n/**\n * Assumes the `logger` provided is a `winston.Logger` at the specified `level`.\n * @param  {Logger} logger `winston` Logger to assert against\n * @param  {String} level Target level logger is expected at.\n */\nhelpers.assertLogger = function (logger, level) {\n  assume(logger).instanceOf(winston.Logger);\n  assume(logger.log).is.a('function');\n  assume(logger.add).is.a('function');\n  assume(logger.remove).is.a('function');\n  assume(logger.level).equals(level || 'info');\n  Object.keys(logger.levels).forEach(function (method) {\n    assume(logger[method]).is.a('function');\n  });\n};\n\n"
  },
  {
    "path": "test/helpers/mocks/legacy-mixed-transport.js",
    "content": "'use strict'\n\nconst events = require('events');\nconst util = require('util')\nconst Transport = require('../../../').Transport;\n\n//\n// ### function LegacyMixed (options)\n// #### @options {Object} Options for this instance.\n// Constructor function for the LegacyMixed transport object responsible\n// for persisting log messages and metadata to a memory array of messages\n// and conforming to the old winston transport API, **BUT** INHERITS FROM\n// THE MODERN WINSTON TRANSPORT.\n//\nmodule.exports = class LegacyMixed extends Transport {\n  constructor(options = {}) {\n    super(options);\n\n    //\n    // Expose the name of this Transport on the prototype\n    //\n    module.exports.prototype.name = 'legacy-mixed-test';\n\n    this.silent = options.silent;\n    this.output = { error: [], write: [] };\n  }\n\n  //\n  // ### function log (level, msg, [meta], callback)\n  // #### @level {string} Level at which to log the message.\n  // #### @msg {string} Message to log\n  // #### @meta {Object} **Optional** Additional metadata to attach\n  // #### @callback {function} Continuation to respond to when complete.\n  // Core logging method exposed to Winston. Metadata is optional.\n  //\n  log(level, msg, meta, callback) {\n    if (this.silent) {\n      return callback(null, true);\n    }\n\n    var output = 'I AM BACKWARDS COMPATIBLE WITH LEGACY';\n\n    if (level === 'error' || level === 'debug') {\n      this.errorOutput.push(output);\n    } else {\n      this.writeOutput.push(output);\n    }\n\n    this.emit('logged');\n    callback(null, true);\n  }\n};\n"
  },
  {
    "path": "test/helpers/mocks/legacy-transport.js",
    "content": "'use strict'\n\nconst events = require('events');\nconst util = require('util')\nconst Transport = require('winston-compat').Transport;\n\n//\n// ### function Legacy (options)\n// #### @options {Object} Options for this instance.\n// Constructor function for the Legacy transport object responsible\n// for persisting log messages and metadata to a memory array of messages\n// and conforming to the old winston transport API.\n//\nconst Legacy = module.exports = function Legacy(options) {\n  options = options || {};\n  Transport.call(this, options);\n\n  this.silent = options.silent;\n  this.output = { error: [], write: [] };\n};\n\n//\n// Inherit from `winston.Transport`.\n//\nutil.inherits(Legacy, Transport);\n\n//\n// Expose the name of this Transport on the prototype\n//\nLegacy.prototype.name = 'legacy-test';\n\n//\n// ### function log (level, msg, [meta], callback)\n// #### @level {string} Level at which to log the message.\n// #### @msg {string} Message to log\n// #### @meta {Object} **Optional** Additional metadata to attach\n// #### @callback {function} Continuation to respond to when complete.\n// Core logging method exposed to Winston. Metadata is optional.\n//\nLegacy.prototype.log = function (level, msg, meta, callback) {\n  if (this.silent) {\n    return callback(null, true);\n  }\n\n  var output = 'I AM BACKWARDS COMPATIBLE WITH LEGACY';\n\n  if (level === 'error' || level === 'debug') {\n    this.errorOutput.push(output);\n  } else {\n    this.writeOutput.push(output);\n  }\n\n  this.emit('logged');\n  callback(null, true);\n};\n"
  },
  {
    "path": "test/helpers/mocks/mock-transport.js",
    "content": "const stream = require('stream')\nconst winston = require('../../../lib/winston');\n\n/**\n * Returns a new Winston transport instance which will invoke\n * the `write` method on each call to `.log`\n *\n * @param {function} write Write function for the specified stream\n * @returns {StreamTransportInstance} A transport instance\n */\nfunction createMockTransport(write) {\n  const writeable = new stream.Writable({\n    objectMode: true,\n    write: write\n  });\n\n  return new winston.transports.Stream({ stream: writeable })\n}\n\nmodule.exports = {\n  createMockTransport\n};\n"
  },
  {
    "path": "test/helpers/scripts/colorize.js",
    "content": "/*\n * colorize.js: A test fixture for logging colorized messages\n *\n * (C) 2015 Tom Spencer\n * MIT LICENCE\n *\n */\n\nvar winston = require('../../../lib/winston');\n\nvar format = winston.format.combine(\n  winston.format.colorize({ message: true }),\n  winston.format.simple()\n);\n\nvar logger = winston.createLogger({\n  format: format,\n  transports: [\n    new winston.transports.Console()\n  ]\n});\n\nlogger.info('Simply a test');\n"
  },
  {
    "path": "test/helpers/scripts/default-rejections.js",
    "content": "/*\n * default-rejectionss.js: A test fixture for logging rejections with the default winston logger.\n *\n * (C) 2011 Charlie Robbins\n * MIT LICENCE\n *\n */\n\nvar path = require(\"path\"),\n  winston = require(\"../../../lib/winston\");\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\nwinston.rejections.handle([\n  new winston.transports.File({\n    filename: path.join(testLogFixturesPath, \"default-rejection.log\"),\n    handleRejections: true\n  })\n]);\n\nwinston.info(\"Log something before error\");\n\nsetTimeout(function() {\n  Promise.reject(new Error(\"OH NOES! It rejected!\"));\n}, 1000);\n"
  },
  {
    "path": "test/helpers/scripts/exit-on-error.js",
    "content": "/*\n * default-exceptions.js: A test fixture for logging exceptions with the default winston logger.\n *\n * (C) 2011 Charlie Robbins\n * MIT LICENCE\n *\n */\n\nvar path = require('path'),\n    winston = require('../../../lib/winston');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\nwinston.exitOnError = function (err) {\n  process.stdout.write(err.message);\n  return err.message !== 'Ignore this error';\n};\n\nwinston.handleExceptions([\n  new winston.transports.File({\n    filename: path.join(testLogFixturesPath, 'exit-on-error.log'),\n    handleExceptions: true\n  })\n]);\n\nsetTimeout(function () {\n  throw new Error('Ignore this error');\n}, 100);\n"
  },
  {
    "path": "test/helpers/scripts/log-rejections.js",
    "content": "/*\n * log-rejections.js: A test fixture for logging rejections in winston.\n *\n * (C) 2011 Charlie Robbins\n * MIT LICENCE\n *\n */\n\nvar path = require(\"path\"),\n  winston = require(\"../../../lib/winston\");\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\nvar logger = winston.createLogger({\n  transports: [\n    new winston.transports.File({\n      filename: path.join(testLogFixturesPath, \"rejections.log\"),\n      handleRejections: true\n    })\n  ]\n});\n\nlogger.rejections.handle();\n\nsetTimeout(function() {\n  Promise.reject(new Error(\"OH NOES! It rejected!\"));\n}, 1000);\n"
  },
  {
    "path": "test/helpers/scripts/unhandle-exceptions.js",
    "content": "/*\n * unhandle-exceptions.js: A test fixture for using `.unhandleExceptions()` winston.\n *\n * (C) 2011 Charlie Robbins\n * MIT LICENCE\n *\n */\n\nvar path = require('path'),\n    winston = require('../../../lib/winston');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\nvar logger = winston.createLogger({\n  transports: [\n    new winston.transports.File({\n      filename: path.join(testLogFixturesPath, 'unhandle-exception.log')\n    })\n  ]\n});\n\nlogger.transports[0].transport.handleExceptions;\n\nlogger.exceptions.handle();\nlogger.exceptions.unhandle();\n\nsetTimeout(function () {\n  throw new Error('OH NOES! It failed!');\n}, 200);\n"
  },
  {
    "path": "test/helpers/scripts/unhandle-rejections.js",
    "content": "/*\n * unhandle-rejections.js: A test fixture for using `.unhandleRejections()` winston.\n *\n * (C) 2011 Charlie Robbins\n * MIT LICENCE\n *\n */\n\nvar path = require('path'),\n  winston = require('../../../lib/winston');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\nvar logger = winston.createLogger({\n  transports: [\n    new winston.transports.File({\n      filename: path.join(testLogFixturesPath, 'unhandle-rejections.log')\n    })\n  ]\n});\n\nlogger.transports[0].transport.handleRejections;\n\nlogger.rejections.handle();\nlogger.rejections.unhandle();\n\nsetTimeout(function () {\n  Promise.reject(new Error('OH NOES! It rejected!'));\n}, 200);\n"
  },
  {
    "path": "test/integration/formats.test.js",
    "content": "/*\n * formats.test.js: Integration tests for winston.format\n *\n * (C) 2015 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nvar path = require('path'),\n    assume = require('assume'),\n    colors = require('@colors/colors/safe'),\n    spawn = require('cross-spawn-async'),\n    winston = require('../../lib/winston'),\n    helpers = require('../helpers');\n\nvar targetScript = path.join(__dirname, '..', 'helpers', 'scripts', 'colorize.js');\n\n/**\n * Spawns the colorizer helper process for checking\n * if colors work in a non-tty environment\n */\nfunction spawnColorizer(callback) {\n  var child = spawn(process.execPath, [targetScript], { stdio: 'pipe' });\n  var data = '';\n\n  child.stdout.setEncoding('utf8')\n  child.stdout.on('data', function (str) { data += str; });\n  child.on('close', function () {\n    callback(null, data);\n  });\n};\n\ndescribe('winston.format.colorize (Integration)', function () {\n  it('non-TTY environment', function (done) {\n    spawnColorizer(function (err, data) {\n      assume(err).equals(null);\n      assume(data).includes('\\u001b[32mSimply a test\\u001b[39m');\n      done();\n    })\n  });\n});\n"
  },
  {
    "path": "test/integration/logger.test.js",
    "content": "const assume = require('assume');\nconst winston = require('../../lib/winston');\n\nconst Logger = winston.Logger;\n\ndescribe('Logger class', () => {\n  it('that Logger class is exported', () => {\n    Logger === require('../../lib/winston/logger');\n  });\n\n  it('can be inherited', () => {\n    class CustomLogger extends Logger {}\n    const instance = new CustomLogger();\n    assume(instance).instanceOf(CustomLogger);\n    assume(instance).instanceOf(Logger);\n  });\n});\n"
  },
  {
    "path": "test/jest.config.integration.js",
    "content": "const baseConfig = require('../jest.config');\n\n/**\n * @type {import('@jest/types').Config.InitialOptions}\n */\nmodule.exports = {\n  ...baseConfig,\n  rootDir: '../',\n  testMatch: [\n    '<rootDir>/test/integration/**/*.test.js'\n  ]\n};\n"
  },
  {
    "path": "test/jest.config.unit.js",
    "content": "const baseConfig = require('../jest.config');\n\n/**\n * @type {import('@jest/types').Config.InitialOptions}\n */\nmodule.exports = {\n  ...baseConfig,\n  rootDir: '../',\n  testMatch: [\n    '<rootDir>/test/unit/**/*.test.js'\n  ],\n  collectCoverage: true\n};\n"
  },
  {
    "path": "test/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"lib\": [\n      \"es6\"\n    ],\n    \"target\": \"es6\",\n    \"noImplicitAny\": true,\n    \"noImplicitThis\": true,\n    \"strictNullChecks\": true,\n    \"baseUrl\": \"./\",\n    \"forceConsistentCasingInFileNames\": true,\n    \"typeRoots\": [\n      \"../node_modules\",\n      \"../node_modules/@types\"\n    ],\n    \"types\": [\n      \"node\",\n      \"logform\",\n      \"winston-transport\"\n    ],\n    \"noEmit\": true\n  },\n  \"files\": [\n    \"typescript-definitions.ts\"\n  ]\n}\n"
  },
  {
    "path": "test/typescript-definitions.ts",
    "content": "import * as winston from '../index';\n\nlet logger: winston.Logger = winston.createLogger({\n    level: 'info',\n    format: winston.format.json(),\n    transports: [\n        new winston.transports.Console({ level: 'info' }),\n    ],\n});\n\nlet err: Error = new Error('ttdt');\nlogger.error('The error was: ', err);\nlogger.log('info', 'hey dude', { foo: 'bar' });\nlogger.log({ level: 'info', message: 'hey dude', meta: { foo: 'bar' } });\n\n// Default logger\nwinston.http('New incoming connection');\nwinston.error('The error was: ', err);\n\nwinston.exceptions.handle(new winston.transports.File({ filename: 'exceptions.log' }));\n\nconst loggerOptions: winston.LoggerOptions = {\n    level: 'info',\n    format: winston.format.json(),\n    transports: [\n        new winston.transports.Console({ level: 'info' }),\n    ],\n};\n\n// assign the returned values to the logger variable,\n// to make sure that the methods have 'Logger' declared as their return type\nlogger = winston.loggers.add('category', loggerOptions);\nlogger = winston.loggers.add('category');\nlogger = winston.loggers.get('category', loggerOptions);\nlogger = winston.loggers.get('category');\n\nconst hasLogger: boolean = winston.loggers.has('category');\nwinston.loggers.close('category');\nwinston.loggers.close();\n\nlet container: winston.Container = new winston.Container(loggerOptions);\nlogger = container.get('testLogger');\n\nlogger = container.loggers.get('testLogger')!;\n\ncontainer.close('testLogger');\n\nconst level = container.options.level;\n\ncontainer = new winston.Container();\nlogger = container.get('testLogger2');\n\nlogger.isLevelEnabled('debug');\nlogger.isErrorEnabled();\nlogger.isWarnEnabled();\nlogger.isInfoEnabled();\nlogger.isVerboseEnabled();\nlogger.isDebugEnabled();\nlogger.isSillyEnabled();\n"
  },
  {
    "path": "test/unit/formats/errors.test.js",
    "content": "/*\n * errors.test.js: E2E Integration tests of `new Error()` handling\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\n'use strict';\n\nconst assume = require('assume');\nconst { LEVEL, MESSAGE, SPLAT } = require('triple-beam');\nconst winston = require('../../../lib/winston');\nconst { format } = winston;\nconst helpers = require('../../helpers');\n\nfunction assumeExpectedInfo(info, target = {}) {\n  const expected = Object.assign({}, {\n    level: 'info',\n    message: 'Errors lack .toJSON() lulz'\n  }, target);\n\n  assume(info).is.an('object');\n  assume(info).includes('level');\n  assume(info).includes('message');\n\n  assume(info.level).equals(expected.level);\n  assume(info[LEVEL]).equals(expected.level);\n  assume(info.message).equals(expected.message);\n  assume(info[MESSAGE]).equals(expected.message);\n\n  Object.keys(expected).forEach(key => {\n    if (key === 'level' || key === 'message') return;\n    assume(info[key]).equals(expected[key]);\n  });\n}\n\ndescribe('format.errors (integration)', function () {\n  it('logger.log(level, error)', (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info);\n      done();\n    }, format.errors());\n\n    logger.log('info', new Error('Errors lack .toJSON() lulz'));\n  });\n\n  it('logger.log(level, error) [custom error properties]', (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        something: true,\n        wut: 'another string'\n      });\n\n      done();\n    }, format.errors());\n\n    const err = new Error('Errors lack .toJSON() lulz');\n    err.something = true;\n    err.wut = 'another string';\n\n    logger.log('info', err);\n  });\n\n  it('logger.log(level, error, meta)', (done) => {\n    const meta = {\n      thisIsMeta: true,\n      anyValue: 'a string'\n    };\n\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, meta);\n      done();\n    }, format.errors());\n\n    logger.log('info', new Error('Errors lack .toJSON() lulz'), meta);\n  });\n\n  it('logger.log(level, error, meta) [custom error properties]', (done) => {\n    const meta = {\n      thisIsMeta: true,\n      anyValue: 'a string'\n    };\n\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, Object.assign({\n        something: true,\n        wut: 'another string'\n      }, meta));\n\n      done();\n    }, format.errors());\n\n    const err = new Error('Errors lack .toJSON() lulz');\n    err.something = true;\n    err.wut = 'another string';\n\n    logger.log('info', err, meta);\n  });\n\n  it('logger.log(level, msg, meta<error>)', (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        message: 'Caught error: Errors lack .toJSON() lulz'\n      });\n\n      done();\n    }, format.combine(\n      format.errors(),\n      format.printf(info => info.message)\n    ));\n\n    logger.log('info', 'Caught error:', new Error('Errors lack .toJSON() lulz'));\n  });\n\n  it('logger.log(level, msg, meta<error>) [custom error properties]', (done) => {\n    const err = new Error('Errors lack .toJSON() lulz');\n    err.something = true;\n    err.wut = 'another string';\n\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        message: 'Caught error: Errors lack .toJSON() lulz',\n        stack: err.stack,\n        something: true,\n        wut: 'another string'\n      });\n\n      done();\n    }, format.combine(\n      format.errors(),\n      format.printf(info => info.message)\n    ));\n\n    logger.log('info', 'Caught error:', err);\n  });\n\n  it('logger.<level>(error)', (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info);\n      done();\n    }, format.errors());\n\n    logger.info(new Error('Errors lack .toJSON() lulz'));\n  });\n\n  it('logger.<level>(error) [custom error properties]', (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        something: true,\n        wut: 'another string'\n      });\n\n      done();\n    }, format.errors());\n\n    const err = new Error('Errors lack .toJSON() lulz');\n    err.something = true;\n    err.wut = 'another string';\n\n    logger.info(err);\n  });\n\n  it('logger.<level>(error, meta)', (done) => {\n    const meta = {\n      thisIsMeta: true,\n      anyValue: 'a string'\n    };\n\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, meta);\n      done();\n    }, format.errors());\n\n    logger.info(new Error('Errors lack .toJSON() lulz'), meta);\n  });\n\n  it('logger.<level>(error, meta) [custom error properties]', (done) => {\n    const meta = {\n      thisIsMeta: true,\n      anyValue: 'a string'\n    };\n\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, Object.assign({\n        something: true,\n        wut: 'another string'\n      }, meta));\n\n      done();\n    }, format.errors());\n\n    const err = new Error('Errors lack .toJSON() lulz');\n    err.something = true;\n    err.wut = 'another string';\n\n    logger.info(err, meta);\n  });\n\n  it('logger.<level>(msg, meta<error>)', (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        message: 'Caught error: Errors lack .toJSON() lulz'\n      });\n\n      done();\n    }, format.combine(\n      format.errors(),\n      format.printf(info => info.message)\n    ));\n\n    logger.info('Caught error:', new Error('Errors lack .toJSON() lulz'));\n  });\n\n  it('logger.<level>(msg, meta<error>) [custom error properties]', (done) => {\n    const err = new Error('Errors lack .toJSON() lulz');\n    err.something = true;\n    err.wut = 'another string';\n\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        message: 'Caught error: Errors lack .toJSON() lulz',\n        stack: err.stack,\n        something: true,\n        wut: 'another string'\n      });\n\n      done();\n    }, format.combine(\n      format.errors(),\n      format.printf(info => info.message)\n    ));\n\n    logger.info('Caught error:', err);\n  });\n\n  it(`Promise.reject().catch(logger.<level>)`, (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, { level: 'error' });\n      done();\n    }, format.errors());\n\n    new Promise((done, reject) => {\n      throw new Error('Errors lack .toJSON() lulz')\n    }).catch(logger.error.bind(logger));\n  });\n\n  it(`Promise.reject().catch(logger.<level>) [custom error properties]`, (done) => {\n    const logger = helpers.createLogger(function (info) {\n      assumeExpectedInfo(info, {\n        level: 'error',\n        something: true,\n        wut: 'a string'\n      });\n\n      done();\n    }, format.errors());\n\n    new Promise((done, reject) => {\n      const err = new Error('Errors lack .toJSON() lulz');\n      err.something = true;\n      err.wut = 'a string';\n\n      throw err;\n    }).catch(logger.error.bind(logger));\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/config/config.test.js",
    "content": "/*\n * config.test.js: Tests for winston.config\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst winston = require('../../../../lib/winston');\n\ndescribe('winston.config', function () {\n  it('should have expected methods', function () {\n    assume(winston.config).is.an('object');\n    assume(winston.config.addColors).is.a('function');\n    assume(winston.config.cli).is.an('object');\n    assume(winston.config.npm).is.an('object');\n    assume(winston.config.syslog).is.an('object');\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/container.test.js",
    "content": "/*\n * container-test.js: Tests for the Container object\n *\n * (C) 2011 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst winston = require('../../../lib/winston');\n\ndescribe('Container', function () {\n  describe('no transports', function () {\n    var container = new winston.Container();\n    var defaultTest;\n\n    it('.add(default-test)', function () {\n      defaultTest = container.add('default-test');\n      assume(defaultTest.log).is.a('function');\n    });\n\n    it('.get(default-test)', function () {\n      assume(container.get('default-test')).equals(defaultTest);\n    });\n\n    it('.has(default-test)', function () {\n      assume(container.has('default-test')).true();\n    });\n\n    it('.has(not-has)', function () {\n      assume(container.has('not-has')).false();\n    });\n\n    it('.close(default-test)', function () {\n      container.close('default-test');\n      assume(container.loggers.has('default-test')).falsy();\n    });\n\n    it('.close(non-existent)', function () {\n      container.close('non-existent');\n      assume(container.loggers.has('non-existent')).falsy();\n    });\n\n    it('.close()', function () {\n      container.close();\n      assume(container.loggers.has()).falsy();\n    });\n  });\n\n  describe('explicit transports', function () {\n    var transports = [new winston.transports.Http({ port: 9412 })];\n    var container = new winston.Container({ transports: transports });\n    var all = {};\n\n    it('.get(some-logger)', function () {\n      all.someLogger = container.get('some-logger');\n      assume(all.someLogger._readableState.pipes).instanceOf(winston.transports.Http);\n      assume(all.someLogger._readableState.pipes).equals(transports[0]);\n    });\n\n    it('.get(some-other-logger)', function () {\n      all.someOtherLogger = container.get('some-other-logger');\n\n      assume(all.someOtherLogger._readableState.pipes).instanceOf(winston.transports.Http);\n      assume(all.someOtherLogger._readableState.pipes).equals(transports[0]);\n      assume(all.someOtherLogger._readableState.pipes).equals(all.someLogger._readableState.pipes);\n    });\n  });\n\n  describe('explicit non-array transport', function () {\n    var transport = new winston.transports.Http({ port: 9412 });\n    var container = new winston.Container({ transports: transport });\n    var all = {};\n\n    it('.get(some-logger)', function () {\n      all.someLogger = container.get('some-logger');\n      assume(all.someLogger._readableState.pipes).instanceOf(winston.transports.Http);\n      assume(all.someLogger._readableState.pipes).equals(transport);\n    });\n\n    it('.get(some-other-logger)', function () {\n      all.someOtherLogger = container.get('some-other-logger');\n\n      assume(all.someOtherLogger._readableState.pipes).instanceOf(winston.transports.Http);\n      assume(all.someOtherLogger._readableState.pipes).equals(transport);\n      assume(all.someOtherLogger._readableState.pipes).equals(all.someLogger._readableState.pipes);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/create-logger.test.js",
    "content": "const winston = require(\"../../../lib/winston\");\nconst assume = require(\"assume\");\nconst isStream = require(\"is-stream\");\nconst {format} = require(\"../../../lib/winston\");\nconst TransportStream = require(\"winston-transport\");\n\ndescribe('Create Logger', function () {\n    it('should build a logger with default values', function () {\n        let logger = winston.createLogger();\n        assume(logger).is.an('object');\n        assume(isStream(logger.format));\n        assume(logger.level).equals('info');\n        assume(logger.exitOnError).equals(true);\n    });\n\n    it('new Logger({ silent: true })', function (done) {\n        const neverLogTo = new TransportStream({\n            log: function (info) {\n                assume(false).true('TransportStream was improperly written to');\n            }\n        });\n\n        var logger = winston.createLogger({\n            transports: [neverLogTo],\n            silent: true\n        });\n\n        logger.log({\n            level: 'info',\n            message: 'This should be ignored'\n        });\n\n        setImmediate(() => done());\n    });\n\n    it('new Logger({ parameters })', function () {\n        let myFormat = format(function (info, opts) {\n            return info;\n        })();\n\n        let logger = winston.createLogger({\n            format: myFormat,\n            level: 'error',\n            exitOnError: false,\n            transports: []\n        });\n\n        assume(logger.format).equals(myFormat);\n        assume(logger.level).equals('error');\n        assume(logger.exitOnError).equals(false);\n        assume(logger._readableState.pipesCount).equals(0);\n    });\n\n    it('new Logger({ levels }) defines custom methods', function () {\n        let myFormat = format(function (info, opts) {\n            return info;\n        })();\n\n        let logger = winston.createLogger({\n            levels: winston.config.syslog.levels,\n            format: myFormat,\n            level: 'error',\n            exitOnError: false,\n            transports: []\n        });\n\n        Object.keys(winston.config.syslog.levels).forEach(level => {\n            assume(logger[level]).is.a('function');\n        })\n    });\n\n    it('new Logger({ levels }) custom methods are not bound to instance', function (done) {\n        let logger = winston.createLogger({\n            level: 'error',\n            exitOnError: false,\n            transports: []\n        });\n\n        let logs = [];\n        let extendedLogger = Object.create(logger, {\n            write: {\n                value: function (...args) {\n                    logs.push(args);\n                    if (logs.length === 4) {\n                        assume(logs.length).is.eql(4);\n                        assume(logs[0]).is.eql([{test: 1, level: 'info'}]);\n                        assume(logs[1]).is.eql([{test: 2, level: 'warn'}]);\n                        assume(logs[2]).is.eql([{message: 'test3', level: 'info'}])\n                        assume(logs[3]).is.eql([{\n                            with: 'meta',\n                            test: 4,\n                            level: 'warn',\n                            message: 'a warning'\n                        }]);\n\n                        done();\n                    }\n                }\n            }\n        });\n\n        extendedLogger.log('info', {test: 1});\n        extendedLogger.log('warn', {test: 2});\n        extendedLogger.info('test3');\n        extendedLogger.warn('a warning', {with: 'meta', test: 4});\n    });\n});\n"
  },
  {
    "path": "test/unit/winston/exception-handler.test.js",
    "content": "/*\n * exception-test.js: Tests for exception data gathering in winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst baseHandlerTests = require('../../helpers/handler-tests');\n\ndescribe('ExceptionHandler', function () {\n  jest.setTimeout(100);\n\n  baseHandlerTests({\n    name: 'ExceptionHandler',\n    helper: 'exceptionHandler',\n    setup: 'clearExceptions',\n    listener: 'uncaughtException',\n    toggleSetting: 'handleExceptions'\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/exception-stream.test.js",
    "content": "/*\n * exception-test.js: Tests for exception data gathering in winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst { Writable } = require('readable-stream');\nconst path = require('path');\nconst winston = require('../../../lib/winston');\nconst ExceptionStream = require('../../../lib/winston/exception-stream');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\nasync function writeToStreamAsync(stream, payload) {\n  return new Promise((resolve, reject) => {\n    stream._write(payload, 'utf8', (err) => {\n      return err ? reject(err) : resolve();\n    });\n  });\n}\n\ndescribe('ExceptionStream', function () {\n  it('has expected methods', function () {\n    var filename = path.join(testLogFixturesPath, 'exception-stream.log');\n    var transport = new winston.transports.File({ filename });\n    var instance = new ExceptionStream(transport);\n\n    assume(instance.handleExceptions).is.true();\n    assume(instance.transport).equals(transport);\n    assume(instance._write).is.a('function');\n    assume(instance).instanceof(ExceptionStream);\n    assume(instance).inherits(Writable);\n  });\n\n  it('throws without a transport', function () {\n    const invalidInstantation = () => new ExceptionStream();\n\n    assume(invalidInstantation).throws('ExceptionStream requires a TransportStream instance.');\n  });\n\n  describe('_write method', function () {\n    let exceptionStream;\n    let fakeTransport;\n    let transportLogCalls;\n    beforeEach(function () {\n      transportLogCalls = [];\n      fakeTransport = {\n        log: (info, callback) => {\n          transportLogCalls.push(info);\n          return setImmediate(callback);\n        }\n      };\n      exceptionStream = new ExceptionStream(fakeTransport);\n    });\n\n    it('should write to the transport when the exception property is false', async function () {\n      const info = {\n        level: 'error',\n        message: 'Test exception message',\n        exception: true,\n        timestamp: new Date().toISOString()\n      };\n\n      await writeToStreamAsync(exceptionStream, info);\n\n      assume(transportLogCalls).to.be.length(1);\n    });\n\n    // eslint-disable-next-line no-undefined\n    const falsyValues = [false, null, undefined, 0, '', NaN];\n    it.each(falsyValues)(\n      'should not write to transport when the exception property is a falsy value of: \"%s\"',\n      async function (falsyValue) {\n        const info = {\n          level: 'error',\n          exception: falsyValue,\n          message: 'Regular log message',\n          timestamp: new Date().toISOString()\n        };\n\n        await writeToStreamAsync(exceptionStream, info);\n\n        assume(transportLogCalls).to.be.length(0);\n      }\n    );\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/log-exception.test.js",
    "content": "/*\n * log-exception.test.js: Tests for exception data gathering in winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst fs = require('fs');\nconst fsPromise = require('node:fs/promises');\nconst path = require('path');\nconst { spawn } = require('child_process');\nconst winston = require('../../../lib/winston');\nconst helpers = require('../../helpers');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\nconst testHelperScriptsPath = path.join(__dirname, '..', '..', 'helpers', 'scripts');\n\ndescribe('Logger, ExceptionHandler', function () {\n  jest.setTimeout(5000);\n\n  describe('.exceptions.unhandle()', function () {\n    it('does not log to any transports', function (done) {\n      var logFile = path.join(testLogFixturesPath, 'unhandle-exception.log');\n\n      helpers.tryUnlink(logFile);\n\n      spawn('node', [path.join(testHelperScriptsPath, 'unhandle-exceptions.js')])\n        .on('exit', function () {\n          fs.exists(logFile, function (exists) {\n            assume(exists).false();\n            done();\n          });\n        });\n    });\n\n    it('handlers immutable', function () {\n      var logger = winston.createLogger({\n        exceptionHandlers: [\n          new winston.transports.Console(),\n          new winston.transports.File({ filename: path.join(testLogFixturesPath, 'filelog.log') })\n        ]\n      });\n\n      assume(logger.exceptions.handlers.size).equals(2);\n      assume(process.listeners('uncaughtException').length).equals(1);\n      logger.exceptions.unhandle();\n      assume(logger.exceptions.handlers.size).equals(2);\n      assume(process.listeners('uncaughtException').length).equals(0);\n    });\n  });\n\n  it('Custom exitOnError function does not exit', function (done) {\n    const child = spawn('node', [path.join(testHelperScriptsPath, 'exit-on-error.js')]);\n    const stdout = [];\n\n    child.stdout.setEncoding('utf8');\n    child.stdout.on('data', function (line) {\n      stdout.push(line);\n    });\n\n    setTimeout(function () {\n      assume(child.killed).false();\n      assume(stdout).deep.equals(['Ignore this error']);\n      child.kill();\n      done();\n    }, 1000);\n  });\n\n  describe('Exception Handler', function () {\n    let filePath;\n    let processExitSpy;\n\n    beforeEach(function () {\n      filePath = path.join(testLogFixturesPath, 'unhandled-exception.log');\n      processExitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});\n    });\n\n    afterEach(async () => {\n      helpers.tryUnlink(filePath);\n      jest.resetAllMocks();\n    });\n\n    describe('should save the error information to the specified file', function () {\n      describe ('with a Custom Logger instance', function () {\n        let logger;\n        beforeEach(function () {\n          filePath = path.join(testLogFixturesPath, 'unhandled-exception.log');\n          processExitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});\n          logger = winston.createLogger({\n            transports: [\n              new winston.transports.File({\n                filename: filePath,\n                handleExceptions: true\n              })\n            ]\n          });\n          logger.exceptions.handle();\n        });\n\n        it('when strings are thrown as errors', async () => {\n          const expectedMessage = 'OMG NEVER DO THIS STRING EXCEPTIONS ARE AWFUL';\n\n          process.emit('uncaughtException', expectedMessage);\n          await new Promise(resolve => setTimeout(resolve, 500));\n\n          expect(processExitSpy).toHaveBeenCalledTimes(1);\n          expect(processExitSpy).toHaveBeenCalledWith(1);\n\n          // Read the log file and verify its contents\n          const contents = await fsPromise.readFile(filePath, { encoding: 'utf8' });\n          const data = JSON.parse(contents);\n\n          // Assert on the log data\n          assume(data).is.an('object');\n          helpers.assertProcessInfo(data.process);\n          helpers.assertOsInfo(data.os);\n          helpers.assertTrace(data.trace);\n          assume(data.message).includes('uncaughtException: ' + expectedMessage);\n        });\n\n        it('with a custom winston.Logger instance', async () => {\n          const expectedMessage = 'OMG NEVER DO THIS STRING EXCEPTIONS ARE AWFUL';\n\n          process.emit('uncaughtException', expectedMessage);\n          await new Promise(resolve => setTimeout(resolve, 500));\n\n          expect(processExitSpy).toHaveBeenCalledTimes(1);\n          expect(processExitSpy).toHaveBeenCalledWith(1);\n\n          // Read the log file and verify its contents\n          const contents = await fsPromise.readFile(filePath, { encoding: 'utf8' });\n          const data = JSON.parse(contents);\n\n          // Assert on the log data\n          assume(data).is.an('object');\n          helpers.assertProcessInfo(data.process);\n          helpers.assertOsInfo(data.os);\n          helpers.assertTrace(data.trace);\n          assume(data.message).includes('uncaughtException: ' + expectedMessage);\n        });\n      });\n\n      it('with the default winston logger', async () => {\n        const expectedMessage = 'OMG NEVER DO THIS STRING EXCEPTIONS ARE AWFUL';\n        winston.exceptions.handle([\n          new winston.transports.File({\n            filename: filePath,\n            handleExceptions: true\n          })\n        ]);\n\n        process.emit('uncaughtException', expectedMessage);\n        await new Promise(resolve => setTimeout(resolve, 500));\n\n        expect(processExitSpy).toHaveBeenCalledTimes(1);\n        expect(processExitSpy).toHaveBeenCalledWith(1);\n\n        // Read the log file and verify its contents\n        const contents = await fsPromise.readFile(filePath, { encoding: 'utf8' });\n        const data = JSON.parse(contents);\n\n        // Assert on the log data\n        assume(data).is.an('object');\n        helpers.assertProcessInfo(data.process);\n        helpers.assertOsInfo(data.os);\n        helpers.assertTrace(data.trace);\n        assume(data.message).includes('uncaughtException: ' + expectedMessage);\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/logger-legacy.test.js",
    "content": "/*\n * logger-legacy.test.js: Tests for Legacy APIs of winston < 3.0.0\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\n'use strict';\n\nconst assume = require('assume');\nconst winston = require('../../../lib/winston');\nconst LegacyTransport = require('../../helpers/mocks/legacy-transport');\nconst LegacyMixedTransport = require('../../helpers/mocks/legacy-mixed-transport');\n\ndescribe('Deprecated APIs', function () {\n  describe('Instantiation Options', function () {\n    const deprecatedOptionTestCases = [\n      { colors: true },\n      { emitErrs: true },\n      { formatters: [] },\n      { padLevels: true },\n      { rewriters: [] },\n      { stripColors: true }\n    ];\n\n    it.each(deprecatedOptionTestCases)('should throw when instantiating with deprecated option of %s', function (option) {\n      const invalidInstantiation = () => winston.createLogger(option);\n\n      assume(invalidInstantiation).throws(/Use a custom/);\n    });\n  });\n\n  describe('Instance methods', function () {\n    const deprecatedMethodTestCases = ['cli'];\n\n    it.each(deprecatedMethodTestCases)(\n      'should throw when invoking deprecated %s() instance method', function (deprecatedMethod) {\n        const logger = winston.createLogger();\n\n        assume(logger[deprecatedMethod]).throws(/Use a custom/);\n      });\n  });\n\n\n  describe('Transports', () => {\n    const legacyTransportTestCases = [\n      {\n        scenario: 'Transport inheriting from winston@2',\n        transport: LegacyTransport\n      },\n      {\n        scenario: 'Transport inheriting from winston@3 but conforming to winston@2 API',\n        transport: LegacyMixedTransport\n      }\n    ];\n\n    describe.each(legacyTransportTestCases)('$scenario', ({ transport: TransportClass }) => {\n      let consoleErrorSpy;\n      let logger;\n      const expectedDeprecationMessage = `${new TransportClass().name} is a legacy winston transport. Consider upgrading`;\n      const getCallsToConsoleError = () => consoleErrorSpy.mock.calls.length;\n      const getFlatConsoleErrorOutput = () => consoleErrorSpy.mock.calls.flat().join('');\n\n      beforeEach(() => {\n        consoleErrorSpy = jest.spyOn(console, 'error');\n      });\n\n      afterEach(() => {\n        jest.resetAllMocks();\n      });\n\n      it(`.add() is successful but logs deprecation notice`, function () {\n        const expectedTransport = new TransportClass();\n        logger = winston.createLogger();\n\n        logger.add(expectedTransport);\n\n        assume(logger._readableState.pipesCount).equals(1);\n        assume(getCallsToConsoleError()).equals(1);\n        assume(getFlatConsoleErrorOutput()).to.include(expectedDeprecationMessage);\n      });\n\n      it(`.add() multiple transports is successful but logs deprecation notice`, function () {\n        logger = winston.createLogger();\n\n        logger.add(new TransportClass());\n        logger.add(new TransportClass());\n        logger.add(new TransportClass());\n\n\n        assume(logger._readableState.pipesCount).equals(3);\n        assume(getCallsToConsoleError()).equals(3);\n        assume(getFlatConsoleErrorOutput()).to.include(expectedDeprecationMessage);\n      });\n\n      it('.remove() is successful', function () {\n        const consoleTransport = new winston.transports.Console();\n        const legacyTransport = new TransportClass();\n\n        logger = winston.createLogger();\n        logger.add(consoleTransport);\n        logger.add(legacyTransport);\n\n        assume(logger.transports.length).equals(2);\n        logger.remove(legacyTransport);\n        assume(logger.transports.length).equals(1);\n        assume(logger.transports[0]).equals(consoleTransport);\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/logger.test.js",
    "content": "/*\n * logger.test.js: Tests for instances of the winston Logger\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\n'use strict';\n\nconst assume = require('assume');\nconst path = require('path');\nconst { EOL } = require('os');\nconst isStream = require('is-stream');\nconst stdMocks = require('std-mocks');\nconst { MESSAGE, SPLAT } = require('triple-beam');\nconst winston = require('../../../lib/winston');\nconst TransportStream = require('winston-transport');\nconst format = require('../../../lib/winston').format;\nconst helpers = require('../../helpers');\nconst mockTransport = require('../../helpers/mocks/mock-transport');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\ndescribe('Logger Instance', function () {\n  describe('Configuration', function () {\n    it('.configure()', function () {\n      let logger = winston.createLogger({\n        transports: [new winston.transports.Console()]\n      });\n\n      assume(logger.transports.length).equals(1);\n      assume(logger.transports[0].name).equals('console');\n\n      logger.configure();\n\n      assume(logger.transports.length).equals(0);\n    });\n\n    it('.configure({ transports })', function () {\n      let logger = winston.createLogger();\n\n      assume(logger.transports.length).equals(0);\n\n      logger.configure({\n        transports: [new winston.transports.Console()]\n      });\n\n      assume(logger.transports.length).equals(1);\n      assume(logger.transports[0].name).equals('console');\n    });\n\n    it('.configure({ transports, format })', function () {\n      let logger = winston.createLogger(),\n          format = logger.format;\n\n      assume(logger.transports.length).equals(0);\n\n      logger.configure({\n        transports: [new winston.transports.Console()],\n        format: winston.format.json()\n      });\n\n      assume(logger.transports.length).equals(1);\n      assume(logger.transports[0].name).equals('console');\n      assume(logger.format).not.equals(format);\n    });\n  });\n\n  describe('Get Highest Log Level', function () {\n    it('should return the highest log level', function () {\n      let logger = winston.createLogger();\n\n      const highestLogLevel = logger.getHighestLogLevel();\n\n      assume(highestLogLevel).equals(2);\n    });\n  });\n\n  describe('Is Log Level Enabled', function () {\n    const defaultLevelTestCases = [\n      'error',\n      'warn',\n      'info',\n      'http',\n      'verbose',\n      'debug',\n      'silly'\n    ];\n\n    it.each(defaultLevelTestCases)('should indicate \"%s\" level is enabled if logger is constructed with that level', function (level) {\n      let logger = winston.createLogger({level});\n\n      const isLevelEnabled = logger.isLevelEnabled(level);\n\n      assume(isLevelEnabled).to.be.true();\n    });\n\n    it('should only enable levels \"info\" and above by default', function () {\n      let logger = winston.createLogger();\n\n      const isHttpEnabled = logger.isLevelEnabled('http');\n      const isInfoEnabled = logger.isLevelEnabled('info');\n      const isWarnEnabled = logger.isLevelEnabled('warn');\n      const isErrorEnabled = logger.isLevelEnabled('error');\n\n      assume(isHttpEnabled).to.be.false();\n      assume(isInfoEnabled).to.be.true();\n      assume(isWarnEnabled).to.be.true();\n      assume(isErrorEnabled).to.be.true();\n    });\n\n    const invalidLevelTestCases = [\n      null,\n      undefined\n    ];\n    it.each(invalidLevelTestCases)('should indicate \"%s\" level is not enabled', function (level) {\n      let logger = winston.createLogger();\n\n      const isLevelEnabled = logger.isLevelEnabled(level);\n\n      assume(isLevelEnabled).to.be.false();\n    });\n\n    it('should indicate all levels are disabled if configured with a level of null', function () {\n      const logger = winston.createLogger({ level: null });\n\n      const levelEnabledResults = [];\n      levelEnabledResults.push(logger.isLevelEnabled('silly'));\n      levelEnabledResults.push(logger.isLevelEnabled('debug'));\n      levelEnabledResults.push(logger.isLevelEnabled('verbose'));\n      levelEnabledResults.push(logger.isLevelEnabled('http'));\n      levelEnabledResults.push(logger.isLevelEnabled('info'));\n      levelEnabledResults.push(logger.isLevelEnabled('warn'));\n      levelEnabledResults.push(logger.isLevelEnabled('error'));\n\n      const isEveryLevelDisabled = levelEnabledResults.every(result => result === false);\n      assume(isEveryLevelDisabled).to.be.true();\n    });\n  });\n\n  describe('Transports', function() {\n    describe('add', function () {\n      it('should throw error when adding an invalid transport', function () {\n        let logger = winston.createLogger();\n        assume(function () {\n          logger.add(5);\n        }).throws(/invalid transport/i);\n      });\n\n      it('should add the expected transport', function (done) {\n        let logger = winston.createLogger();\n        let expected = {message: 'foo', level: 'info'};\n        let transport = new TransportStream({\n          log: function (info) {\n            assume(info.message).equals('foo');\n            assume(info.level).equals('info');\n            assume(JSON.parse(info[MESSAGE])).deep.equals({level: 'info', message: 'foo'});\n            done();\n          }\n        });\n\n        logger.add(transport);\n        logger.log(expected);\n      });\n\n      it('should allow adding multiple transports', function () {\n        let transports = [\n          new winston.transports.File({\n            name: 'filelog-info.log',\n            filename: path.join(testLogFixturesPath, 'filelog-info.log'),\n            level: 'info'\n          }),\n          new winston.transports.File({\n            name: 'filelog-error.log',\n            filename: path.join(testLogFixturesPath, 'filelog-error.log'),\n            level: 'error'\n          })\n        ];\n        let logger = winston.createLogger({\n          transports: transports\n        });\n\n        assume(logger.transports.length).equals(2);\n        assume(logger.transports.map(function (wrap) {\n          return wrap.transport || wrap;\n        })).deep.equals(transports);\n      });\n    });\n\n    describe('remove', function () {\n      it('should do nothing if transport was not added', function () {\n        let transports = [\n          new winston.transports.Console(),\n          new winston.transports.File({filename: path.join(testLogFixturesPath, 'filelog.log')})\n        ];\n\n        let logger = winston.createLogger({transports: transports})\n            .remove(new winston.transports.Console());\n\n        assume(logger.transports.length).equals(2);\n        assume(logger.transports.map(function (wrap) {\n          // Unwrap LegacyTransportStream instances\n          return wrap.transport || wrap;\n        })).deep.equals(transports);\n      });\n\n      it('should remove transport when matching one is found', function () {\n        let transports = [\n          new winston.transports.Console(),\n          new winston.transports.File({filename: path.join(testLogFixturesPath, 'filelog.log')})\n        ];\n\n        let logger = winston.createLogger({transports: transports});\n\n        assume(logger.transports.length).equals(2);\n        logger.remove(transports[0]);\n        assume(logger.transports.length).equals(1);\n        assume(logger.transports[0]).equals(transports[1]);\n      });\n\n      it('should remove specified logger even when duplicate exists', function () {\n        let transports = [\n          new winston.transports.File({\n            name: 'filelog-info.log',\n            filename: path.join(testLogFixturesPath, 'filelog-info.log'),\n            level: 'info'\n          }),\n          new winston.transports.File({\n            name: 'filelog-error.log',\n            filename: path.join(testLogFixturesPath, 'filelog-error.log'),\n            level: 'error'\n          })\n        ];\n        let logger = winston.createLogger({\n          transports: transports\n        });\n\n        logger.remove(transports[0]);\n        assume(logger.transports.length).equals(1);\n        assume(logger.transports[0]).equals(transports[1]);\n      });\n    });\n\n    describe('clear', function () {\n      it('should do nothing when no transports exist', function () {\n        let logger = winston.createLogger();\n        assume(logger.transports.length).equals(0);\n        logger.clear();\n        assume(logger.transports.length).equals(0);\n      });\n\n      it('should remove all transports', function () {\n        let logger = winston.createLogger({\n          transports: [new winston.transports.Console()]\n        });\n\n        assume(logger.transports.length).equals(1);\n        logger.clear();\n        assume(logger.transports.length).equals(0);\n      });\n    });\n\n    describe('stream', function () {\n      it('should return a log stream for all transports', function () {\n        let logger = winston.createLogger();\n        let outStream = logger.stream();\n\n        assume(isStream(outStream)).true();\n      });\n    });\n  });\n\n  describe('Log Levels', function () {\n    it('report unknown levels', function () {\n      const consoleErrorSpy = jest.spyOn(console, 'error');\n      let logger = winston.createLogger();\n\n      logger.log({ message: 'foo', level: 'bar' });\n\n      assume(consoleErrorSpy.mock.calls[0]).deep.equals(['[winston] Unknown logger level: %s', 'bar']);\n    });\n\n    it('.<level>()', function (done) {\n      let logger = helpers.createLogger(function (info) {\n        assume(info).is.an('object');\n        assume(info.level).equals('info');\n        assume(info.message).is.a('string');\n        assume(info[MESSAGE]).is.a('string');\n        assume(info.message).equals('');\n        assume(JSON.parse(info[MESSAGE])).deep.equals({\n          level: 'info',\n          message: ''\n        });\n\n        done();\n      });\n\n      logger.info();\n      logger.info('');\n    });\n\n    it('default levels', function (done) {\n      let logger = winston.createLogger();\n      let expected = {message: 'foo', level: 'debug'};\n\n      function logLevelTransport(level) {\n        return new TransportStream({\n          level: level,\n          log: function (obj) {\n            if (level === 'info') {\n              assume(obj).equals(undefined, 'Transport on level info should never be called');\n            }\n\n            assume(obj.message).equals('foo');\n            assume(obj.level).equals('debug');\n            assume(JSON.parse(obj[MESSAGE])).deep.equals({level: 'debug', message: 'foo'});\n            done();\n          }\n        });\n      }\n\n      assume(logger.info).is.a('function');\n      assume(logger.debug).is.a('function');\n\n      logger\n          .add(logLevelTransport('info'))\n          .add(logLevelTransport('debug'))\n          .log(expected);\n    });\n\n    it('custom levels', function (done) {\n      let logger = winston.createLogger({\n        levels: {\n          bad: 0,\n          test: 1,\n          ok: 2\n        }\n      });\n\n      let expected = {message: 'foo', level: 'test'};\n\n      function filterLevelTransport(level) {\n        return new TransportStream({\n          level: level,\n          log: function (obj) {\n            if (level === 'bad') {\n              assume(obj).equals(undefined, 'transport on level \"bad\" should never be called');\n            }\n\n            assume(obj.message).equals('foo');\n            assume(obj.level).equals('test');\n            assume(JSON.parse(obj[MESSAGE])).deep.equals({level: 'test', message: 'foo'});\n            done();\n          }\n        });\n      }\n\n      assume(logger.bad).is.a('function');\n      assume(logger.test).is.a('function');\n      assume(logger.ok).is.a('function');\n\n      logger\n          .add(filterLevelTransport('bad'))\n          .add(filterLevelTransport('ok'))\n          .log(expected);\n    });\n\n    it('sets transports levels', done => {\n      let logger;\n      const transport = new TransportStream({\n        log(obj) {\n          if (obj.level === 'info') {\n            assume(obj).equals(undefined, 'Transport on level info should never be called');\n          }\n\n          assume(obj.message).equals('foo');\n          assume(obj.level).equals('error');\n          assume(JSON.parse(obj[MESSAGE])).deep.equals({level: 'error', message: 'foo'});\n          done();\n        }\n      });\n\n      // Begin our test in the next tick after the pipe event is\n      // emitted from the transport.\n      transport.once('pipe', () => setImmediate(() => {\n        const expectedError = {message: 'foo', level: 'error'};\n        const expectedInfo = {message: 'bar', level: 'info'};\n\n        assume(logger.error).is.a('function');\n        assume(logger.info).is.a('function');\n\n        // Set the level\n        logger.level = 'error';\n\n        // Log the messages. \"info\" should never arrive.\n        logger\n            .log(expectedInfo)\n            .log(expectedError);\n      }));\n\n      logger = winston.createLogger({\n        transports: [transport]\n      });\n    });\n\n    describe('Log Levels Enabled', function () {\n      it('default levels', function () {\n        let logger = winston.createLogger({\n          level: 'verbose',\n          levels: winston.config.npm.levels,\n          transports: [new winston.transports.Console()]\n        });\n\n        assume(logger.getHighestLogLevel).is.a('function');\n        assume(logger.getHighestLogLevel()).equals(4);\n\n        assume(logger.isLevelEnabled).is.a('function');\n\n        assume(logger.isErrorEnabled).is.a('function');\n        assume(logger.isWarnEnabled).is.a('function');\n        assume(logger.isInfoEnabled).is.a('function');\n        assume(logger.isVerboseEnabled).is.a('function');\n        assume(logger.isDebugEnabled).is.a('function');\n        assume(logger.isSillyEnabled).is.a('function');\n\n        assume(logger.isLevelEnabled('error')).true();\n        assume(logger.isLevelEnabled('warn')).true();\n        assume(logger.isLevelEnabled('info')).true();\n        assume(logger.isLevelEnabled('verbose')).true();\n        assume(logger.isLevelEnabled('debug')).false();\n        assume(logger.isLevelEnabled('silly')).false();\n\n        assume(logger.isErrorEnabled()).true();\n        assume(logger.isWarnEnabled()).true();\n        assume(logger.isInfoEnabled()).true();\n        assume(logger.isVerboseEnabled()).true();\n        assume(logger.isDebugEnabled()).false();\n        assume(logger.isSillyEnabled()).false();\n      });\n\n      it('default levels, transport override', function () {\n        let transport = new winston.transports.Console();\n        transport.level = 'debug';\n\n        let logger = winston.createLogger({\n          level: 'info',\n          levels: winston.config.npm.levels,\n          transports: [transport]\n        });\n\n        assume(logger.getHighestLogLevel).is.a('function');\n        assume(logger.getHighestLogLevel()).equals(5);\n\n        assume(logger.isLevelEnabled).is.a('function');\n\n        assume(logger.isErrorEnabled).is.a('function');\n        assume(logger.isWarnEnabled).is.a('function');\n        assume(logger.isInfoEnabled).is.a('function');\n        assume(logger.isVerboseEnabled).is.a('function');\n        assume(logger.isDebugEnabled).is.a('function');\n        assume(logger.isSillyEnabled).is.a('function');\n\n        assume(logger.isLevelEnabled('error')).true();\n        assume(logger.isLevelEnabled('warn')).true();\n        assume(logger.isLevelEnabled('info')).true();\n        assume(logger.isLevelEnabled('verbose')).true();\n        assume(logger.isLevelEnabled('debug')).true();\n        assume(logger.isLevelEnabled('silly')).false();\n\n        assume(logger.isErrorEnabled()).true();\n        assume(logger.isWarnEnabled()).true();\n        assume(logger.isInfoEnabled()).true();\n        assume(logger.isVerboseEnabled()).true();\n        assume(logger.isDebugEnabled()).true();\n        assume(logger.isSillyEnabled()).false();\n      });\n\n      it('default levels, no transports', function () {\n        let logger = winston.createLogger({\n          level: 'verbose',\n          levels: winston.config.npm.levels,\n          transports: []\n        });\n\n        assume(logger.getHighestLogLevel).is.a('function');\n        assume(logger.getHighestLogLevel()).equals(4);\n\n        assume(logger.isLevelEnabled).is.a('function');\n\n        assume(logger.isErrorEnabled).is.a('function');\n        assume(logger.isWarnEnabled).is.a('function');\n        assume(logger.isInfoEnabled).is.a('function');\n        assume(logger.isVerboseEnabled).is.a('function');\n        assume(logger.isDebugEnabled).is.a('function');\n        assume(logger.isSillyEnabled).is.a('function');\n\n        assume(logger.isLevelEnabled('error')).true();\n        assume(logger.isLevelEnabled('warn')).true();\n        assume(logger.isLevelEnabled('info')).true();\n        assume(logger.isLevelEnabled('verbose')).true();\n        assume(logger.isLevelEnabled('debug')).false();\n        assume(logger.isLevelEnabled('silly')).false();\n\n        assume(logger.isErrorEnabled()).true();\n        assume(logger.isWarnEnabled()).true();\n        assume(logger.isInfoEnabled()).true();\n        assume(logger.isVerboseEnabled()).true();\n        assume(logger.isDebugEnabled()).false();\n        assume(logger.isSillyEnabled()).false();\n      });\n\n      it('custom levels', function () {\n        let logger = winston.createLogger({\n          level: 'test',\n          levels: {\n            bad: 0,\n            test: 1,\n            ok: 2\n          },\n          transports: [new winston.transports.Console()]\n        });\n\n        assume(logger.getHighestLogLevel).is.a('function');\n        assume(logger.getHighestLogLevel()).equals(1);\n\n        assume(logger.isLevelEnabled).is.a('function');\n\n        assume(logger.isBadEnabled).is.a('function');\n        assume(logger.isTestEnabled).is.a('function');\n        assume(logger.isOkEnabled).is.a('function');\n\n        assume(logger.isLevelEnabled('bad')).true();\n        assume(logger.isLevelEnabled('test')).true();\n        assume(logger.isLevelEnabled('ok')).false();\n\n        assume(logger.isBadEnabled()).true();\n        assume(logger.isTestEnabled()).true();\n        assume(logger.isOkEnabled()).false();\n      });\n\n      it('custom levels, no transports', function () {\n        let logger = winston.createLogger({\n          level: 'test',\n          levels: {\n            bad: 0,\n            test: 1,\n            ok: 2\n          },\n          transports: []\n        });\n\n        assume(logger.getHighestLogLevel).is.a('function');\n        assume(logger.getHighestLogLevel()).equals(1);\n\n        assume(logger.isLevelEnabled).is.a('function');\n\n        assume(logger.isBadEnabled).is.a('function');\n        assume(logger.isTestEnabled).is.a('function');\n        assume(logger.isOkEnabled).is.a('function');\n\n        assume(logger.isLevelEnabled('bad')).true();\n        assume(logger.isLevelEnabled('test')).true();\n        assume(logger.isLevelEnabled('ok')).false();\n\n        assume(logger.isBadEnabled()).true();\n        assume(logger.isTestEnabled()).true();\n        assume(logger.isOkEnabled()).false();\n      });\n\n      it('custom levels, transport override', function () {\n        let transport = new winston.transports.Console();\n        transport.level = 'ok';\n\n        let logger = winston.createLogger({\n          level: 'bad',\n          levels: {\n            bad: 0,\n            test: 1,\n            ok: 2\n          },\n          transports: [transport]\n        });\n\n        assume(logger.getHighestLogLevel).is.a('function');\n        assume(logger.getHighestLogLevel()).equals(2);\n\n        assume(logger.isLevelEnabled).is.a('function');\n\n        assume(logger.isBadEnabled).is.a('function');\n        assume(logger.isTestEnabled).is.a('function');\n        assume(logger.isOkEnabled).is.a('function');\n\n        assume(logger.isLevelEnabled('bad')).true();\n        assume(logger.isLevelEnabled('test')).true();\n        assume(logger.isLevelEnabled('ok')).true();\n\n        assume(logger.isBadEnabled()).true();\n        assume(logger.isTestEnabled()).true();\n        assume(logger.isOkEnabled()).true();\n      });\n    })\n  });\n\n  describe('Transport Events', function () {\n    it(`'finish' event awaits transports to emit 'finish'`, function (done) {\n      const transports = [\n        new TransportStream({\n          log: function () {\n          }\n        }),\n        new TransportStream({\n          log: function () {\n          }\n        }),\n        new TransportStream({\n          log: function () {\n          }\n        })\n      ];\n\n      const finished = [];\n      const logger = winston.createLogger({transports});\n\n      // Assert each transport emits finish\n      transports.forEach((transport, i) => {\n        transport.on('finish', () => finished[i] = true);\n      });\n\n      // Manually end the last transport to simulate mixed\n      // finished state\n      transports[2].end();\n\n      // Assert that all transport 'finish' events have been\n      // emitted when the logger emits 'finish'.\n      logger.on('finish', function () {\n        assume(finished[0]).true();\n        assume(finished[1]).true();\n        assume(finished[2]).true();\n        done();\n      });\n\n      setImmediate(() => logger.end());\n    });\n\n    it('error', (done) => {\n      const consoleTransport = new winston.transports.Console();\n      const logger = winston.createLogger({\n        transports: [consoleTransport]\n      });\n\n      logger.on('error', (err, transport) => {\n        assume(err).instanceOf(Error);\n        assume(transport).is.an('object');\n        done();\n      });\n      consoleTransport.emit('error', new Error());\n    });\n\n    it('warn', (done) => {\n      const consoleTransport = new winston.transports.Console();\n      const logger = winston.createLogger({\n        transports: [consoleTransport]\n      });\n\n      logger.on('warn', (err, transport) => {\n        assume(err).instanceOf(Error);\n        assume(transport).is.an('object');\n        done();\n      });\n      consoleTransport.emit('warn', new Error());\n    });\n  })\n\n  describe('Formats', function () {\n    it(`rethrows errors from user-defined formats`, function () {\n      stdMocks.use();\n      const logger = winston.createLogger({\n        transports: [new winston.transports.Console()],\n        format: winston.format.printf((info) => {\n          // Set a trap.\n          if (info.message === 'ENDOR') {\n            throw new Error('ITS A TRAP!');\n          }\n\n          return info.message;\n        })\n      });\n\n      // Trigger the trap.  Swallow the error so processing continues.\n      try {\n        logger.info('ENDOR');\n      } catch (err) {\n        assume(err.message).equals('ITS A TRAP!');\n      }\n\n      const expected = [\n        'Now witness the power of the fully armed and operational logger',\n        'Consider the philosophical and metaphysical – BANANA BANANA BANANA',\n        'I was god once. I saw – you were doing well until everyone died.'\n      ];\n\n      expected.forEach(msg => logger.info(msg));\n\n      stdMocks.restore();\n      const actual = stdMocks.flush();\n      assume(actual.stdout).deep.equals(expected.map(msg => `${msg}${EOL}`));\n      assume(actual.stderr).deep.equals([]);\n    });\n  })\n\n  describe('Profiling', function () {\n    it('ending profiler with object argument should be included in output', function (done) {\n      let logger = helpers.createLogger(function (info) {\n        assume(info).is.an('object');\n        assume(info.something).equals('ok');\n        assume(info.level).equals('info');\n        assume(info.durationMs).is.a('number');\n        assume(info.message).equals('testing1');\n        assume(info[MESSAGE]).is.a('string');\n        done();\n      });\n\n      logger.profile('testing1');\n      setTimeout(function () {\n        logger.profile('testing1', {\n          something: 'ok',\n          level: 'info'\n        })\n      }, 100);\n    });\n\n    // TODO: Revisit if this is a valid test\n    it('calling profile with a callback function should not make a difference', function (done) {\n      let logger = helpers.createLogger(function (info) {\n        assume(info).is.an('object');\n        assume(info.something).equals('ok');\n        assume(info.level).equals('info');\n        assume(info.durationMs).is.a('number');\n        assume(info.message).equals('testing2');\n        assume(info[MESSAGE]).is.a('string');\n        done();\n      });\n\n      logger.profile('testing2', function () {\n        done(new Error('Unexpected callback invoked'));\n      });\n\n      setTimeout(function () {\n        logger.profile('testing2', {\n          something: 'ok',\n          level: 'info'\n        })\n      }, 100);\n    });\n\n    it('should stop a timer when `done` is called on it', function (done) {\n      let logger = helpers.createLogger(function (info) {\n        assume(info).is.an('object');\n        assume(info.something).equals('ok');\n        assume(info.level).equals('info');\n        assume(info.durationMs).is.a('number');\n        assume(info.message).equals('testing1');\n        assume(info[MESSAGE]).is.a('string');\n        done();\n      });\n\n      let timer = logger.startTimer();\n      setTimeout(function () {\n        timer.done({\n          message: 'testing1',\n          something: 'ok',\n          level: 'info'\n        });\n      }, 100);\n    });\n  });\n\n  // TODO: Revisit to improve these\n  describe('Logging non-primitive data types', function () {\n    describe('.log', function () {\n      it(`.log(new Error()) uses Error instance as info`, function (done) {\n        const err = new Error('test');\n        err.level = 'info';\n\n        const logger = helpers.createLogger(function (info) {\n          assume(info).instanceOf(Error);\n          assume(info).equals(err);\n          done();\n        });\n\n        logger.log(err);\n      });\n\n      it(`.info('Hello') preserve meta without splat format`, function (done) {\n        const logged = [];\n        const logger = helpers.createLogger(function (info, enc, next) {\n          logged.push(info);\n          assume(info.label).equals('world');\n          next();\n\n          if (logged.length === 1) done();\n        });\n\n        logger.info('Hello', {label: 'world'});\n      });\n\n      it(`.info('Hello %d') does not mutate unnecessarily with string interpolation tokens`, function (done) {\n        const logged = [];\n        const logger = helpers.createLogger(function (info, enc, next) {\n          logged.push(info);\n          assume(info.label).equals(undefined);\n          next();\n\n          if (logged.length === 1) done();\n        });\n\n        logger.info('Hello %j', {label: 'world'}, {extra: true});\n      });\n\n      it(`.info('Hello') and .info('Hello %d') preserve meta with splat format`, function (done) {\n        const logged = [];\n        const logger = helpers.createLogger(function (info, enc, next) {\n          logged.push(info);\n          assume(info.label).equals('world');\n          next();\n\n          if (logged.length === 2) done();\n        }, format.splat());\n\n        logger.info('Hello', {label: 'world'});\n        logger.info('Hello %d', 100, {label: 'world'});\n      });\n    });\n\n    describe('.info', function () {\n      it('.info(undefined) creates info with { message: undefined }', function (done) {\n        const logger = helpers.createLogger(function (info) {\n          assume(info.message).equals(undefined);\n          done();\n        });\n\n        logger.info(undefined);\n      });\n\n      it('.info(null) creates info with { message: null }', function (done) {\n        const logger = helpers.createLogger(function (info) {\n          assume(info.message).equals(null);\n          done();\n        });\n\n        logger.info(null);\n      });\n\n      it('.info(new Error()) uses Error instance as info', function (done) {\n        const err = new Error('test');\n        const logger = helpers.createLogger(function (info) {\n          assume(info).instanceOf(Error);\n          assume(info).equals(err);\n          done();\n        });\n\n        logger.info(err);\n      });\n\n      it.todo(`https://github.com/winstonjs/winston/issues/2103`);\n    });\n  });\n\n  describe('Metadata Precedence', function () {\n    describe('Should support child loggers & defaultMeta', () => {\n      it('sets child meta for text messages correctly', (done) => {\n        const assertFn = ((msg) => {\n          assume(msg.level).equals('info');\n          assume(msg.message).equals('dummy message');\n          assume(msg.requestId).equals('451');\n          done();\n        });\n\n        const logger = winston.createLogger({\n          transports: [\n            mockTransport.createMockTransport(assertFn)\n          ]\n        });\n\n        const childLogger = logger.child({requestId: '451'});\n        childLogger.info('dummy message');\n      });\n\n      it('sets child meta for json messages correctly', (done) => {\n        const assertFn = ((msg) => {\n          assume(msg.level).equals('info');\n          assume(msg.message.text).equals('dummy');\n          assume(msg.requestId).equals('451');\n          done();\n        });\n\n        const logger = winston.createLogger({\n          transports: [\n            mockTransport.createMockTransport(assertFn)\n          ]\n        });\n\n        const childLogger = logger.child({requestId: '451'});\n        childLogger.info({text: 'dummy'});\n      });\n\n      it('merges child and provided meta correctly', (done) => {\n        const assertFn = ((msg) => {\n          assume(msg.level).equals('info');\n          assume(msg.message).equals('dummy message');\n          assume(msg.service).equals('user-service');\n          assume(msg.requestId).equals('451');\n          done();\n        });\n\n        const logger = winston.createLogger({\n          transports: [\n            mockTransport.createMockTransport(assertFn)\n          ]\n        });\n\n        const childLogger = logger.child({service: 'user-service'});\n        childLogger.info('dummy message', {requestId: '451'});\n      });\n\n      it('provided meta take precedence over defaultMeta', (done) => {\n        const assertFn = ((msg) => {\n          assume(msg.level).equals('info');\n          assume(msg.message).equals('dummy message');\n          assume(msg.service).equals('audit-service');\n          assume(msg.requestId).equals('451');\n          done();\n        });\n\n        const logger = winston.createLogger({\n          defaultMeta: {service: 'user-service'},\n          transports: [\n            mockTransport.createMockTransport(assertFn)\n          ]\n        });\n\n        logger.info('dummy message', {\n          requestId: '451',\n          service: 'audit-service'\n        });\n      });\n\n      it('provided meta take precedence over child meta', (done) => {\n        const assertFn = ((msg) => {\n          assume(msg.level).equals('info');\n          assume(msg.message).equals('dummy message');\n          assume(msg.service).equals('audit-service');\n          assume(msg.requestId).equals('451');\n          done();\n        });\n\n        const logger = winston.createLogger({\n          transports: [\n            mockTransport.createMockTransport(assertFn)\n          ]\n        });\n\n        const childLogger = logger.child({service: 'user-service'});\n        childLogger.info('dummy message', {\n          requestId: '451',\n          service: 'audit-service'\n        });\n      });\n\n      it('handles error stack traces in child loggers correctly', (done) => {\n        const assertFn = ((msg) => {\n          assume(msg.level).equals('error');\n          assume(msg.message).equals('dummy error');\n          assume(msg.stack).includes('logger.test.js');\n          assume(msg.service).equals('user-service');\n          assume(msg.cause.message).equals('dummy error cause');\n          assume(msg.cause.stack).includes('logger.test.js');\n          done();\n        });\n\n        const logger = winston.createLogger({\n          transports: [\n            mockTransport.createMockTransport(assertFn)\n          ]\n        });\n\n        const childLogger = logger.child({service: 'user-service'});\n        childLogger.error(Error('dummy error', { cause: Error('dummy error cause') }));\n      });\n\n      it('defaultMeta() autobinds correctly', (done) => {\n        const logger = helpers.createLogger(info => {\n          assume(info.message).equals('test');\n          done();\n        });\n\n        const log = logger.info;\n        log('test');\n      });\n    });\n  });\n\n  describe('Backwards Compatability', function () {\n    describe('Winston V2 Log', function () {\n      it('.log(level, message)', function (done) {\n        let logger = helpers.createLogger(function (info) {\n          assume(info).is.an('object');\n          assume(info.level).equals('info');\n          assume(info.message).equals('Some super awesome log message');\n          assume(info[MESSAGE]).is.a('string');\n          done();\n        });\n\n        logger.log('info', 'Some super awesome log message')\n      });\n\n      it(`.log(level, undefined) creates info with { message: undefined }`, function (done) {\n        const logger = helpers.createLogger(function (info) {\n          assume(info.message).equals(undefined);\n          done();\n        });\n\n        logger.log('info', undefined);\n      });\n\n      it(`.log(level, null) creates info with { message: null }`, function (done) {\n        const logger = helpers.createLogger(function (info) {\n          assume(info.message).equals(null);\n          done();\n        });\n\n        logger.log('info', null);\n      });\n\n      it(`.log(level, new Error()) uses Error instance as info`, function (done) {\n        const err = new Error('test');\n        const logger = helpers.createLogger(function (info) {\n          assume(info).instanceOf(Error);\n          assume(info).equals(err);\n          done();\n        });\n\n        logger.log('info', err);\n      });\n\n      it('.log(level, message, meta)', function (done) {\n        let meta = {one: 2};\n        let logger = helpers.createLogger(function (info) {\n          assume(info).is.an('object');\n          assume(info.level).equals('info');\n          assume(info.message).equals('Some super awesome log message');\n          assume(info.one).equals(2);\n          assume(info[MESSAGE]).is.a('string');\n          done();\n        });\n\n        logger.log('info', 'Some super awesome log message', meta);\n      });\n\n      it('.log(level, formatStr, ...splat)', function (done) {\n        const format = winston.format.combine(\n            winston.format.splat(),\n            winston.format.printf(info => `${info.level}: ${info.message}`)\n        );\n\n        let logger = helpers.createLogger(function (info) {\n          assume(info).is.an('object');\n          assume(info.level).equals('info');\n          assume(info.message).equals('100% such wow {\"much\":\"javascript\"}');\n          assume(info[SPLAT]).deep.equals([100, 'wow', {much: 'javascript'}]);\n          assume(info[MESSAGE]).equals('info: 100% such wow {\"much\":\"javascript\"}');\n          done();\n        }, format);\n\n        logger.log('info', '%d%% such %s %j', 100, 'wow', {much: 'javascript'});\n      });\n\n      it('.log(level, formatStr, ...splat, meta)', function (done) {\n        const format = winston.format.combine(\n            winston.format.splat(),\n            winston.format.printf(info => `${info.level}: ${info.message} ${JSON.stringify({thisIsMeta: info.thisIsMeta})}`)\n        );\n\n        let logger = helpers.createLogger(function (info) {\n          assume(info).is.an('object');\n          assume(info.level).equals('info');\n          assume(info.message).equals('100% such wow {\"much\":\"javascript\"}');\n          assume(info[SPLAT]).deep.equals([100, 'wow', {much: 'javascript'}]);\n          assume(info.thisIsMeta).true();\n          assume(info[MESSAGE]).equals('info: 100% such wow {\"much\":\"javascript\"} {\"thisIsMeta\":true}');\n          done();\n        }, format);\n\n        logger.log('info', '%d%% such %s %j', 100, 'wow', {much: 'javascript'}, {thisIsMeta: true});\n      });\n\n      it(`.log(level, new Error()) creates info with error cause`, function (done) {\n        const errCause = new Error(\"error cause\");\n        const err = new Error('test', { cause: errCause });\n        const logger = helpers.createLogger(function (info) {\n          assume(info).instanceOf(Error);\n          assume(info).equals(err);\n          assume(info.cause).equals(errCause)\n          done();\n        });\n\n        logger.log('info', err);\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/profiler.test.js",
    "content": "/*\n * profiler.js: Tests for exception simple profiling.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst Logger = require('../../../lib/winston/logger');\nconst Profiler = require('../../../lib/winston/profiler');\nconst { PassThrough } = require('stream');\ndescribe('Profiler', function () {\n  it('new Profiler()', function () {\n    assume(function () {\n      new Profiler();\n    }).throws('Logger is required for profiling');\n  });\n\n  it('.done({ info })', function (done) {\n    const logger = new Logger();\n    logger.write = function (info) {\n      assume(info).is.an('object');\n      assume(info.something).equals('ok');\n      assume(info.level).equals('info');\n      assume(info.durationMs).is.a('number');\n      assume(info.message).equals('testing1');\n      done();\n    };\n    var profiler = new Profiler(logger);\n    setTimeout(function () {\n      profiler.done({\n        something: 'ok',\n        level: 'info',\n        message: 'testing1'\n      });\n    }, 200);\n  });\n\n  it('non logger object', function(){\n    assume(function() {\n      new Profiler(new Error('Unknown error'));\n    }).throws('Logger is required for profiling');\n\n    assume(function () {\n      new Profiler({a:'b'});\n    }).throws('Logger is required for profiling');\n\n    assume(function(){\n      new Profiler([1,2,3,4]);\n    }).throws('Logger is required for profiling');\n\n    assume(function () {\n      new Profiler(new PassThrough());\n    }).throws('Logger is required for profiling');\n\n    assume(function () {\n      new Profiler(2);\n    }).throws('Logger is required for profiling');\n    \n    assume(function () {\n      new Profiler('1');\n    }).throws('Logger is required for profiling');\n  })\n});\n"
  },
  {
    "path": "test/unit/winston/rejection-handler.test.js",
    "content": "/*\n * rejection-test.js: Tests for rejection data gathering in winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst baseHandlerTests = require('../../helpers/handler-tests');\n\ndescribe('UnhandledRejectionHandler', function () {\n  jest.setTimeout(100);\n\n  baseHandlerTests({\n    name: 'RejectionHandler',\n    helper: 'rejectionHandler',\n    setup: 'clearRejections',\n    listener: 'unhandledRejection',\n    toggleSetting: 'handleRejections'\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/tail-file.test.js",
    "content": "/*\n * tail-file.test.js: Tests for lib/winston/tail-file.js\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst fs = require('fs');\nconst path = require('path');\nconst winston = require('../../../lib/winston');\nconst tailFile = require('../../../lib/winston/tail-file');\nconst { Stream } = require('readable-stream');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', 'fixtures', 'logs');\n\n//\n// Test helper that performs writes to a specific log file\n// on a given interval\n//\nfunction logOnInterval(opts, done) {\n  var filename = opts.file;\n  var interval = opts.interval || 100;\n  var timeout = opts.timeout || 10 * 1000;\n  var message = opts.message || '';\n  var open = opts.open;\n  var transport = new winston.transports.File({ filename: filename });\n  var logger = winston.createLogger({ transports: [transport] });\n\n  if (open) {\n    transport.once('open', open);\n  }\n\n  let counters = {\n    write: 0,\n    read: 0\n  };\n\n  fs.unlink(filename, function () {\n    const intervalId = setInterval(function () {\n      logger.info({ message: ++counters.write + message });\n    }, interval);\n\n    setTimeout(function () {\n      //\n      // Clear the interval to stop writes, then pause\n      // briefly to let any listening streams flush.\n      //\n      clearInterval(intervalId);\n      setTimeout(done.bind(null, null, counters), 100);\n    }, timeout);\n  });\n}\n\n\ndescribe('tailFile', function () {\n  jest.setTimeout(10 * 1000);\n\n  it('is a function', function () {\n    assume(tailFile).is.a('function');\n    assume(tailFile.length).equals(2);\n  });\n\n  it('returns a stream that emits \"line\" for every line', function (done) {\n    var tailable = path.join(testLogFixturesPath, 'common-tail-file.log');\n    var expected = 0;\n    //\n    // Performs the actual tail and asserts it.\n    //\n    function startTailFile() {\n      var stream = tailFile({ file: tailable });\n      assume(stream).instanceof(Stream);\n\n      stream.on('line', function (buff) {\n        expected += 1;\n        assume(JSON.parse('' + buff)).is.an('object');\n      });\n    }\n\n    logOnInterval({\n      file: tailable,\n      open: startTailFile,\n      timeout: 5000\n    }, function (err, actual) {\n      assume(expected).equals(actual.write);\n      done();\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/transports/00-file-stress.test.js",
    "content": "'use strict';\n\n/*\n * file-stress.test.js: Tests for stressing File transport: volume, ambient event loop lag.\n *\n * (C) 2016 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst fs = require('fs');\nconst os  = require('os');\nconst path = require('path');\nconst assume = require('assume');\nconst helpers = require('../../../helpers');\nconst split = require('split2');\nconst winston = require('../../../../lib/winston');\n\ndescribe('File (stress)', function () {\n  jest.setTimeout(30 * 1000);\n\n  const fileStressLogFile = path.resolve(__dirname, '../../../fixtures/logs/file-stress-test.log');\n  beforeEach(function () {\n    try {\n      fs.unlinkSync(fileStressLogFile);\n    } catch (ex) {\n      if (ex && ex.code !== 'ENOENT') { return done(ex); }\n    }\n  });\n\n  it('should handle a high volume of writes', function (done) {\n    const logger = winston.createLogger({\n      transports: [new winston.transports.File({\n        filename: fileStressLogFile\n      })]\n    });\n\n    const counters = {\n      write: 0,\n      read: 0\n    };\n\n    const interval = setInterval(function () {\n      logger.info(++counters.write);\n    }, 0);\n\n    setTimeout(function () {\n      clearInterval(interval);\n\n      helpers.tryRead(fileStressLogFile)\n        .on('error', function (err) {\n          assume(err).false();\n          logger.close();\n          done();\n        })\n        .pipe(split())\n        .on('data', function (d) {\n          const json = JSON.parse(d);\n          assume(json.level).equal('info');\n          assume(json.message).equal(++counters.read);\n        })\n        .on('end', function () {\n          assume(counters.write).equal(counters.read);\n          logger.close();\n          done();\n        });\n    }, 10000);\n  });\n\n  it('should handle a high volume of large writes', function (done) {\n    const logger = winston.createLogger({\n      transports: [new winston.transports.File({\n        filename: fileStressLogFile\n      })]\n    });\n\n    const counters = {\n      write: 0,\n      read: 0\n    };\n\n    const interval = setInterval(function () {\n      const msg = {\n        counter: ++counters.write,\n        message: 'a'.repeat(16384 - os.EOL.length - 1)\n      };\n      logger.info(msg);\n    }, 0);\n\n    setTimeout(function () {\n      clearInterval(interval);\n\n      helpers.tryRead(fileStressLogFile)\n        .on('error', function (err) {\n          assume(err).false();\n          logger.close();\n          done();\n        })\n        .pipe(split())\n        .on('data', function (d) {\n          const json = JSON.parse(d);\n          assume(json.level).equal('info');\n          assume(json.message).equal('a'.repeat(16384 - os.EOL.length - 1));\n          assume(json.counter).equal(++counters.read);\n        })\n        .on('end', function () {\n          assume(counters.write).equal(counters.read);\n          logger.close();\n          done();\n        });\n    }, 10000);\n  });\n\n  it('should handle a high volume of large writes synchronous', function (done) {\n    const logger = winston.createLogger({\n      transports: [new winston.transports.File({\n        filename: fileStressLogFile\n      })]\n    });\n\n    const counters = {\n      write: 0,\n      read: 0\n    };\n\n    const msgs = new Array(10).fill().map(() => ({\n      counter: ++counters.write,\n      message: 'a'.repeat(16384 - os.EOL.length - 1)\n    }));\n    msgs.forEach(msg => logger.info(msg));\n\n    setTimeout(function () {\n      helpers.tryRead(fileStressLogFile)\n        .on('error', function (err) {\n          assume(err).false();\n          logger.close();\n          done();\n        })\n        .pipe(split())\n        .on('data', function (d) {\n          const json = JSON.parse(d);\n          assume(json.level).equal('info');\n          assume(json.message).equal('a'.repeat(16384 - os.EOL.length - 1));\n          assume(json.counter).equal(++counters.read);\n        })\n        .on('end', function () {\n          assume(counters.write).equal(counters.read);\n          logger.close();\n          done();\n        });\n    }, 10000);\n  });\n\n  it('should handle a high volume of writes with lazy option enabled', function (done) {\n    const logger = winston.createLogger({\n      transports: [\n        new winston.transports.File({\n          filename: fileStressLogFile,\n          lazy: true\n        })\n      ]\n    });\n\n    const counters = {\n      write: 0,\n      read: 0\n    };\n\n    const interval = setInterval(function () {\n      logger.info(++counters.write);\n    }, 0);\n\n    setTimeout(function () {\n      clearInterval(interval);\n\n      helpers\n        .tryRead(fileStressLogFile)\n        .on('error', function (err) {\n          assume(err).false();\n          logger.close();\n          done();\n        })\n        .pipe(split())\n        .on('data', function (d) {\n          const json = JSON.parse(d);\n          assume(json.level).equal('info');\n          assume(json.message).equal(++counters.read);\n        })\n        .on('end', function () {\n          assume(counters.write).equal(counters.read);\n          logger.close();\n          done();\n        });\n    }, 10000);\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/transports/console.test.js",
    "content": "'use strict';\n\n/*\n * console-test.js: Tests for instances of the Console transport\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst { LEVEL, MESSAGE } = require('triple-beam');\nconst winston = require('../../../../lib/winston');\nconst stdMocks = require('std-mocks');\n\nconst defaultLevels = winston.config.npm.levels;\nconst transports = {\n  defaults: new winston.transports.Console(),\n  noStderr: new winston.transports.Console({ stderrLevels: [] }),\n  stderrLevels: new winston.transports.Console({\n    stderrLevels: ['info', 'error']\n  }),\n  consoleWarnLevels: new winston.transports.Console({\n    consoleWarnLevels: ['warn', 'debug']\n  }),\n  eol: new winston.transports.Console({ eol: 'X' }),\n  syslog: new winston.transports.Console({\n    levels: winston.config.syslog.levels\n  }),\n  customLevelStderr: new winston.transports.Console({\n    levels: {\n      alpha: 0,\n      beta: 1,\n      gamma: 2,\n      delta: 3,\n      epsilon: 4,\n    },\n    stderrLevels: ['delta', 'epsilon']\n  })\n};\n\n/**\n * Returns a function that asserts the `transport` has the specified\n * logLevels values in the appropriate logLevelsName member.\n *\n * @param  {TransportStream} transport Transport to assert against\n * @param  {Array} logLevels Set of levels assumed to exist for the specified map\n * @param  {String} logLevelsName The name of the array/map that holdes the log leveles values (ie: 'stderrLevels', 'consoleWarnLevels')\n * @return {function} Assertion function to execute comparison\n */\nfunction assertLogLevelsValues(transport, logLevels, logLevelsName = 'stderrLevels') {\n  return function () {\n    assume(JSON.stringify(Object.keys(transport[logLevelsName]).sort()))\n      .equals(JSON.stringify(logLevels.sort()));\n  };\n}\n\n\n\ndescribe('Console transport', function () {\n  describe('with defaults', function () {\n    it('logs all levels to stdout', function () {\n      stdMocks.use();\n      transports.defaults.levels = defaultLevels;\n      Object.keys(defaultLevels)\n        .forEach(function (level) {\n          const info = {\n            [LEVEL]: level,\n            message: `This is level ${level}`,\n            level\n          };\n\n          info[MESSAGE] = JSON.stringify(info);\n          transports.defaults.log(info);\n        });\n\n      stdMocks.restore();\n      var output = stdMocks.flush();\n      assume(output.stderr).is.an('array');\n      assume(output.stderr).length(0);\n      assume(output.stdout).is.an('array');\n      assume(output.stdout).length(7);\n    });\n\n    it(\"should set stderrLevels to [] by default\", assertLogLevelsValues(\n      transports.defaults,\n      [],\n      'stderrLevels'\n    ));\n  });\n\n  describe('throws an appropriate error when', function () {\n    it(\"if stderrLevels is set, but not an Array { stderrLevels: 'Not an Array' }\", function () {\n      assume(function () {\n        let throwing = new winston.transports.Console({\n          stderrLevels: 'Not an Array'\n        })\n      }).throws(/Cannot make set from type other than Array of string elements/);\n    });\n\n    it(\"if stderrLevels contains non-string elements { stderrLevels: ['good', /^invalid$/, 'valid']\", function () {\n      assume(function () {\n        let throwing = new winston.transports.Console({\n          stderrLevels: ['good', /^invalid$/, 'valid']\n        })\n      }).throws(/Cannot make set from type other than Array of string elements/);\n    });\n  });\n\n  it(\"{ stderrLevels: ['info', 'error'] } logs to them appropriately\", assertLogLevelsValues(\n    transports.stderrLevels,\n    ['info', 'error'],\n    'stderrLevels'\n  ));\n  it(\"{ consoleWarnLevels: ['warn', 'debug'] } logs to them appropriately\", assertLogLevelsValues(\n    transports.consoleWarnLevels,\n    ['warn', 'debug'],\n    'consoleWarnLevels'\n  ));\n\n  it('{ eol } adds a custom EOL delimiter', function (done) {\n    stdMocks.use();\n    transports.eol.log({ [MESSAGE]: 'info: testing. 1 2 3...' }, function () {\n      stdMocks.restore();\n\n      var output = stdMocks.flush(),\n          line   = output.stdout[0];\n\n      assume(line).equal('info: testing. 1 2 3...X');\n      done();\n    });\n  });\n});\n\n\n// TODO(invalid-test): test is no longer valid as we don't have the vows dependency anymore\n// vows.describe('winston/transports/console').addBatch({\n//   \"An instance of the Console Transport\": {\n//     \"with syslog levels\": {\n//       \"should have the proper methods defined\": function () {\n//         helpers.assertConsole(syslogTransport);\n//       },\n//       \"the log() method\": helpers.testSyslogLevels(syslogTransport, \"should respond with true\", function (ign, err, logged) {\n//         assert.isNull(err);\n//         assert.isTrue(logged);\n//       })\n//     }\n//   }\n// }).addBatch({\n//   \"An instance of the Console Transport with no options\": {\n//     \"should log only 'error' and 'debug' to stderr\": helpers.testLoggingToStreams(\n//       winston.config.npm.levels, defaultTransport, ['debug', 'error'], stdMocks\n//     )\n//   }\n// }).addBatch({\n//   \"An instance of the Console Transport with debugStdout set\": {\n//     \"should set stderrLevels to 'error' by default\": helpers.assertStderrLevels(\n//       debugStdoutTransport,\n//       ['error']\n//     ),\n//     \"should log only the 'error' level to stderr\": helpers.testLoggingToStreams(\n//       winston.config.npm.levels, debugStdoutTransport, ['error'], stdMocks\n//     )\n//   }\n// }).addBatch({\n//   \"An instance of the Console Transport with stderrLevels set\": {\n//     \"should log only the levels in stderrLevels to stderr\": helpers.testLoggingToStreams(\n//       winston.config.npm.levels, stderrLevelsTransport, ['info', 'warn'], stdMocks\n//     )\n//   }\n// }).addBatch({\n//   \"An instance of the Console Transport with stderrLevels set to an empty array\": {\n//     \"should log only to stdout, and not to stderr\": helpers.testLoggingToStreams(\n//       winston.config.npm.levels, noStderrTransport, [], stdMocks\n//     )\n//   }\n// }).addBatch({\n//   \"An instance of the Console Transport with custom levels and stderrLevels set\": {\n//     \"should log only the levels in stderrLevels to stderr\": helpers.testLoggingToStreams(\n//       customLevels, customLevelsAndStderrTransport, ['delta', 'epsilon'], stdMocks\n//     )\n//   }\n// }).export(module);\n"
  },
  {
    "path": "test/unit/winston/transports/error.test.js",
    "content": "const winston = require('../../../../lib/winston');\nconst assume = require('assume');\n\n// https://github.com/winstonjs/winston/issues/1364\ndescribe('transports issue 1364', () => {\n  const mainError = 'Error logging!';\n  const otherError = 'Other error';\n  let logger;\n  let errorMessage;\n  let counter;\n  let maxCounter;\n  let logError;\n  let transport;\n  const newTransport = () =>\n    Object.assign(new winston.transports.Console(), {\n      log: (info, next) => {\n        if (counter === maxCounter) {\n          next(new Error(errorMessage));\n          return;\n        }\n        if (logError !== null) {\n          errorMessage = otherError;\n        }\n        counter = counter + 1;\n        next();\n        return;\n      }\n    });\n  beforeEach(() => {\n    errorMessage = mainError;\n    counter = 0;\n    maxCounter = 1;\n    logError = null;\n    transport = newTransport();\n    logger = winston.createLogger({\n      level: 'info',\n      transports: [transport]\n    });\n    logger.on('error', error => {\n      counter = 0;\n      logError = error;\n    });\n  });\n\n  describe('only log once', () => {\n    beforeEach(() => {\n      logger.info('log once');\n    });\n\n    it('logger transport has single correct transport', () => {\n      const transports = logger.transports;\n      assume(transports).is.an('array');\n      assume(transports).length(1);\n      assume(transports).contains(transport);\n    });\n\n    it(\"error didn't\", () => {\n      assume(logError).not.exists();\n    });\n  });\n\n  describe('log twice', () => {\n    beforeEach(() => {\n      logger.info('log twice 1');\n      logger.info('log twice 2'); // this raises the `mainError` for the transport\n    });\n\n    it('logger transport has single correct transport', () => {\n      const transports = logger.transports;\n      assume(transports).is.an('array');\n      assume(transports).length(1);\n      assume(transports).contains(transport);\n    });\n\n    it('error occurred', () => {\n      assume(logError).property('message', mainError);\n    });\n  });\n\n  describe('log thrice', () => {\n    beforeEach(() => {\n      logger.info('log thrice 1');\n      logger.info('log thrice 2'); // this raises the `mainError` for the transport\n      logger.info('log thrice 3');\n    });\n\n    it('logger transport has single correct transport', () => {\n      const transports = logger.transports;\n      assume(transports).is.an('array');\n      assume(transports).length(1);\n      assume(transports).contains(transport);\n    });\n\n    it('error occurred', () => {\n      assume(logError).property('message', mainError);\n    });\n  });\n\n  describe('log four times', () => {\n    beforeEach(() => {\n      logger.info('log four times 1');\n      logger.info('log four times 2'); // this raises the `mainError` for the transport\n      logger.info('log four times 3');\n      logger.info('log four times 4'); // this raises the `otherError` for the transport\n    });\n\n    it('logger transport has single correct transport', () => {\n      const transports = logger.transports;\n      assume(transports).is.an('array');\n      assume(transports).length(1);\n      assume(transports).contains(transport);\n    });\n\n    it('other error occurred', () => {\n      assume(logError).property('message', otherError);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/transports/file-create-dir.test.js",
    "content": "'use strict';\n\nconst fs = require('fs');\nconst assert = require('assert');\nconst path = require('path');\nconst winston = require('../../../../lib/winston');\nconst { rimraf } = require('rimraf');\n\n/* eslint-disable no-sync */\n\ndescribe('winston/transports/file/createLogDir', function () {\n  const logDir = path.resolve(__dirname, '../../../fixtures/temp_logs');\n\n  beforeEach(function () {\n    return rimraf(logDir).catch(err => {\n      if (err){\n        console.log('Error encountered when removing `temp_logs` dir')\n        console.log(err);\n      }\n    })\n  });\n\n  it('should create directory if it does not exist', function () {\n    winston.createLogger({\n      transports: [\n        new winston.transports.File({\n          filename: path.join(logDir, 'file.log')\n        })\n      ]\n    });\n\n    assert(fs.existsSync(logDir));\n  });\n\n  it('should create directory if it does not exist when write to the stream', function () {\n    const streamfile = path.join(logDir, 'simple-stream.log');\n    const stream = fs.createWriteStream(streamfile);\n\n    winston.createLogger({\n      transports: [\n        new winston.transports.File({\n          stream: stream\n        })\n      ]\n    });\n\n    assert(fs.existsSync(logDir));\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/transports/file.test.js",
    "content": "'use strict';\n\n/* eslint-disable no-sync */\nconst assert = require('assert');\nconst { rimraf } = require('rimraf');\nconst fs = require('fs');\nconst fsPromise = require('node:fs/promises');\nconst path = require('path');\nconst winston = require('../../../../lib/winston');\nconst testLogFixturesPath = path.join(__dirname, '..', '..', '..', 'fixtures', 'logs');\nconst { MESSAGE } = require('triple-beam');\n\n/**\n * Sends logs to the provided transport. Supports logging a specified total data size at a given chunk size.\n *\n * @param {Object} transport - The winston transport to log to.\n * @param {Object} [opts={}] - Options for logging.\n * @param {number} [opts.kbytes=1] - The number of kilobytes to log.\n * @param {string} [opts.char='A'] - The character to use for logging.\n * @param {number} [opts.chunkSize=1] - The size of each log chunk in kilobytes.\n * @returns {Promise<void>} A promise that resolves when logging is complete.\n */\nasync function logToTransport(transport, opts = {}) {\n  const chunkSize = opts.chunkSize ?? 1; // Default chunk size to 1KB if not provided\n  const char = opts.char ?? 'A'; // Default character to 'A' if not provided\n  const totalKBytes = opts.kbytes ?? 1; // Default total size to 1KB if not provided\n\n  const bytesPerChunk = chunkSize * 1024 - 1; // Convert kilobytes to bytes and account for newline character\n  const kbStr = char.repeat(bytesPerChunk); // create chunk of desired size with specified character\n\n  for (let i = 0; i < totalKBytes; i++) {\n    const logPayload = { level: 'info', [MESSAGE]: kbStr };\n    await new Promise((resolve, reject) => {\n      transport.log(logPayload, (err) => {\n        return err ? reject() : resolve();\n      });\n    });\n  }\n}\n\n/**\n * Waits for a file to exist by repeatedly checking for its presence.\n *\n * @param {string} filename - The name of the file to wait for.\n * @param {number} [timeout=1000] - Maximum time to wait in milliseconds before throwing an error.\n * @param {number} [interval=20] - Interval in milliseconds between file existence checks.\n * @returns {Promise<void>} A promise that resolves when the file exists or rejects on timeout.\n * @throws {Error} If the file does not exist after the timeout period.\n */\nasync function waitForFile(filename, timeout = 1000, interval = 20) {\n  const start = Date.now();\n  const filepath = getFilePath(filename);\n  while (Date.now() - start < timeout) {\n    try {\n      await fsPromise.access(filepath);\n      return; // File exists\n    } catch {\n      // File doesn't exist yet, keep waiting\n    }\n    await new Promise(r => setTimeout(r, interval));\n  }\n  throw new Error(`Timed out waiting for file: ${filename}`);\n}\n\nasync function removeFixtures() {\n  await rimraf(path.join(testLogFixturesPath, 'test*'), { glob: true });\n}\nfunction getFilePath(filename) {\n  return path.join(testLogFixturesPath, filename);\n}\nconst assertFileExists = (filename) => {\n  assert.doesNotThrow(\n    () => fs.statSync(getFilePath(filename)),\n    `Expected file ${filename} to exist`\n  );\n};\nconst assertFileDoesNotExist = (filename) => {\n  assert.throws(\n    () => fs.statSync(getFilePath(filename)),\n    `Expected file ${filename} to not exist`\n  );\n};\nconst assertFileContentsStartWith = (filename, char) => {\n  const fileContents = fs.readFileSync(getFilePath(filename), 'utf8');\n  assert.strictEqual(\n    fileContents[0],\n    char,\n    `Content of file ${filename} was not filled with ${char}`\n  );\n};\nconst assertFileSizeLessThan = (filename, maxSizeBytes) => {\n  const stats = fs.statSync(getFilePath(filename));\n  assert.ok(\n    stats.size <= maxSizeBytes,\n    `Expected file ${filename} to not exceed ${maxSizeBytes} bytes, but was ${stats.size} bytes`\n  );\n};\n\ndescribe('File Transport', function () {\n  const defaultTransportOptions = {\n    timestamp: true,\n    json: false,\n    filename: 'testarchive.log',\n    dirname: testLogFixturesPath,\n    maxsize: 4096\n  };\n\n  beforeEach(async () => {\n    await removeFixtures();\n  });\n\n  afterEach(async () => {\n    await removeFixtures();\n  });\n\n  describe('Construction', () => {\n    const conflictingOptionTestCases = [\n      { stream: true, filename: true },\n      { stream: true, dirname: true },\n      { stream: true, maxsize: true }\n    ];\n    it.each(conflictingOptionTestCases)('should throw an error if conflicting options are provided', (opts) => {\n      const instantition = () => new winston.transports.File(opts);\n\n      assert.throws(instantition, 'Conflicting options did not result in an error');\n    });\n  });\n\n  describe('Filename Option', function () {\n    it('should log to the file with the given filename', async function () {\n      const expectedFilename = 'testfilename.log';\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        filename: expectedFilename\n      });\n\n      await logToTransport(transport);\n      await waitForFile(expectedFilename);\n\n      assertFileExists(expectedFilename);\n    });\n  });\n\n  describe('Rotation Format option', function () {\n    it('should create multiple files correctly with rotation Function', async function () {\n      let i = 0;\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        rotationFormat: () => `_${i++}`\n      });\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive.log');\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive_1.log');\n\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive_1.log');\n    });\n  });\n\n  describe('Archive option', function () {\n    it('should archive log file when max size is exceeded', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        zippedArchive: true\n      });\n\n      await logToTransport(transport, { kbytes: 1 });\n      await waitForFile('testarchive.log');\n      assertFileExists('testarchive.log');\n      assertFileDoesNotExist('testarchive1.log');\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive1.log');\n      assertFileExists('testarchive.log.gz');\n      assertFileExists('testarchive1.log');\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive2.log');\n      assertFileExists('testarchive1.log.gz');\n      assertFileExists('testarchive2.log');\n    });\n\n    it('should not archive log file when max size is exceeded', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        zippedArchive: false\n      });\n\n      await logToTransport(transport, { kbytes: 1 });\n      await waitForFile('testarchive.log');\n      assertFileExists('testarchive.log');\n      assertFileDoesNotExist('testarchive1.log');\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive1.log');\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive1.log');\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive2.log');\n      assertFileExists('testarchive1.log');\n      assertFileExists('testarchive2.log');\n    });\n  });\n\n  describe('Maxsize option', function () {\n    it('should create a new file the configured max size is exceeded', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        maxsize: 2048\n      });\n\n      await logToTransport(transport, { kbytes: 1 });\n      await waitForFile('testarchive.log');\n\n      await logToTransport(transport, { kbytes: 2 });\n      await waitForFile('testarchive1.log');\n\n      // Verify both files exist after rotation\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive1.log');\n    });\n\n    it('should not exceed max size for any file', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        maxsize: 2048\n      });\n\n      await logToTransport(transport, { kbytes: 3 });\n      await waitForFile('testarchive.log');\n\n      await logToTransport(transport, { kbytes: 2 });\n      await waitForFile('testarchive1.log');\n      await waitForFile('testarchive2.log');\n\n      // Verify both files exist after rotation\n      assertFileSizeLessThan('testarchive.log', 2048);\n      assertFileSizeLessThan('testarchive1.log', 2048);\n      assertFileSizeLessThan('testarchive2.log', 2048);\n    });\n  });\n\n  describe('Maxfiles option', function () {\n    it('should not exceed the max files', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        maxsize: 2024, // Small size to trigger frequent rotations\n        maxFiles: 3, // Only allow 3 files total\n        lazy: true\n      });\n\n      // Log well beyond enough data to create 3 files\n      await logToTransport(transport);\n      await logToTransport(transport);\n      await logToTransport(transport);\n      await logToTransport(transport);\n      await logToTransport(transport);\n      await logToTransport(transport);\n      await logToTransport(transport);\n\n      // Wait for the last expected file\n      await new Promise(resolve => setTimeout(resolve, 5000));\n\n      // Should have 3 files total (maxFiles)\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive1.log');\n      assertFileDoesNotExist('testarchive3.log'); // This should not exist because maxFiles = 3\n    }, 10000);\n\n    it('should delete the oldest file when maxfiles is met', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        maxsize: 1024, // Small size to trigger frequent rotations\n        maxFiles: 2, // Only allow 2 files total\n        lazy: true // Ensure files are created immediately\n      });\n\n      // Create first log file\n      await logToTransport(transport);\n      await waitForFile('testarchive.log');\n\n      // Create second log file\n      await logToTransport(transport);\n      await waitForFile('testarchive1.log');\n\n      // Create third log file (should delete the oldest one)\n      await logToTransport(transport, { kbytes: 0.5 });\n      await waitForFile('testarchive2.log');\n\n      // Should only have 2 most recent files (maxFiles = 2)\n      assertFileDoesNotExist('testarchive.log'); // The oldest file should be deleted\n      assertFileExists('testarchive1.log');\n      assertFileExists('testarchive2.log');\n    });\n  });\n\n  describe('Tailable option', function () {\n    // eslint-disable-next-line max-statements\n    it('should write to original file and older files will be in ascending order', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        maxFiles: 4,\n        tailable: true\n      });\n\n      // We need to log enough data to create 3 files of 4KB each = 12KB total\n      await logToTransport(transport, { kbytes: 4, char: 'A' });\n      await waitForFile('testarchive.log');\n      await logToTransport(transport, { kbytes: 4, char: 'B' });\n      await waitForFile('testarchive1.log');\n      await logToTransport(transport, { kbytes: 4, char: 'C' });\n      await waitForFile('testarchive2.log');\n      await logToTransport(transport, { kbytes: 1, char: 'D' });\n      await waitForFile('testarchive3.log');\n\n      // Verify the expected files exist and their contents are correct\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive1.log');\n      assertFileExists('testarchive2.log');\n      assertFileExists('testarchive3.log');\n\n      // Verify the contents of the files are in the expected order\n      assertFileContentsStartWith('testarchive.log', 'D');\n      assertFileContentsStartWith('testarchive1.log', 'C');\n      assertFileContentsStartWith('testarchive2.log', 'B');\n      // FIX: I would expect the first file that was rolled to be filled with the first log message\n      // instead the file is empty. Investigation needed.\n      // assertFileContentsStartWith('testarchive3.log', 'A');\n    });\n\n    it('should write to the newest file and older files will be in descending order', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        tailable: false\n      });\n\n      // We need to log enough data to create 3 files of 4KB each = 12KB total\n      await logToTransport(transport, { kbytes: 4, char: 'A' });\n      await waitForFile('testarchive.log');\n      await logToTransport(transport, { kbytes: 4, char: 'B' });\n      await waitForFile('testarchive1.log');\n      await logToTransport(transport, { kbytes: 4, char: 'C' });\n      await waitForFile('testarchive2.log');\n\n      // Verify the expected files exist\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive1.log');\n      assertFileExists('testarchive2.log');\n\n      // Verify the contents of the files are in the expected order\n      // eslint-disable-next-line -- intentionally asserting file starts with no values\n      assertFileContentsStartWith('testarchive.log', undefined);\n      // FIX: only two of the files are filled and are not in the expected order. File contents are as follows:\n      //   file testarchive.log  - empty\n      //   file testarchive1.log - 'B'\n      //   file testarchive2.log - 'C'\n      //   file testarchive3.log - empty\n      // assertFileContentsStartWith('testarchive1.log', 'A');\n      // assertFileContentsStartWith('testarchive2.log', 'B');\n    });\n  });\n\n  describe('Lazy option', () => {\n    it('should not create log file until needed when lazy is enabled', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        lazy: true\n      });\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive.log');\n\n      assertFileExists('testarchive.log');\n      assertFileDoesNotExist('testarchive1.log');\n    });\n\n    it('should create log files on initializaiton when lazy is enabled', async function () {\n      const transport = new winston.transports.File({\n        ...defaultTransportOptions,\n        lazy: false\n      });\n\n      await logToTransport(transport, { kbytes: 4 });\n      await waitForFile('testarchive.log');\n\n      assertFileExists('testarchive.log');\n      assertFileExists('testarchive1.log');\n      assertFileDoesNotExist('testarchive2.log');\n    });\n  });\n\n\n  describe('Stream Option', function () {\n    it.todo('should display the deprecation notice');\n    it.todo('should write to the stream when logged to with expected object');\n  });\n\n  describe('Flushing on end (issue #1504)', function () {\n    it('should flush all messages to file when logger.end() is called', async function () {\n      const expectedFilename = 'test-flush.log';\n      const expectedMessageCount = 100;\n\n      const logger = winston.createLogger({\n        transports: [\n          new winston.transports.File({\n            filename: expectedFilename,\n            dirname: testLogFixturesPath\n          })\n        ]\n      });\n\n      // Log multiple messages\n      for (let i = 0; i < expectedMessageCount; i++) {\n        logger.info(`message ${i}`);\n      }\n      logger.info('THE LAST MESSAGE');\n\n      // Wait for logger to finish\n      await new Promise((resolve) => {\n        logger.on('finish', resolve);\n        logger.end();\n      });\n\n      // Verify all messages were written\n      await waitForFile(expectedFilename);\n      const fileContents = fs.readFileSync(getFilePath(expectedFilename), 'utf8');\n      const lines = fileContents.split('\\n').filter(l => l.trim());\n\n      assert.strictEqual(\n        lines.length,\n        expectedMessageCount + 1,\n        `Expected ${expectedMessageCount + 1} lines, got ${lines.length}`\n      );\n      assert.ok(\n        fileContents.includes('THE LAST MESSAGE'),\n        'File should contain THE LAST MESSAGE'\n      );\n    });\n\n    it('should flush all messages when transport finish event is used', async function () {\n      const expectedFilename = 'test-flush-transport.log';\n      const expectedMessageCount = 50;\n\n      const transport = new winston.transports.File({\n        filename: expectedFilename,\n        dirname: testLogFixturesPath\n      });\n\n      const logger = winston.createLogger({\n        transports: [transport]\n      });\n\n      // Log multiple messages\n      for (let i = 0; i < expectedMessageCount; i++) {\n        logger.info(`message ${i}`);\n      }\n\n      // Wait for transport to finish (original issue pattern)\n      await new Promise((resolve) => {\n        transport.on('finish', resolve);\n        logger.end();\n      });\n\n      // Verify all messages were written\n      await waitForFile(expectedFilename);\n      const fileContents = fs.readFileSync(getFilePath(expectedFilename), 'utf8');\n      const lines = fileContents.split('\\n').filter(l => l.trim());\n\n      assert.strictEqual(\n        lines.length,\n        expectedMessageCount,\n        `Expected ${expectedMessageCount} lines, got ${lines.length}`\n      );\n    });\n  });\n\n\n  // TODO: Reintroduce these tests\n  //\n  // \"Error object in metadata #610\": {\n  //   topic: function () {\n  //     var myErr = new Error(\"foo\");\n  //\n  //     fileTransport.log('info', 'test message', myErr, this.callback.bind(this, null, myErr));\n  //   },\n  //   \"should not be modified\": function (err, myErr) {\n  //     assert.equal(myErr.message, \"foo\");\n  //     // Not sure if this is the best possible way to check if additional props appeared\n  //     assert.deepEqual(Object.getOwnPropertyNames(myErr), Object.getOwnPropertyNames(new Error(\"foo\")));\n  //   }\n  // }\n  //\n  // \"Date object in metadata\": {\n  //   topic: function () {\n  //     var obj = new Date(1000);\n  //     fileTransport.log('info', 'test message', obj, this.callback.bind(this, null, obj));\n  //   },\n  //   \"should not be modified\": function (err, obj) {\n  //     // Not sure if this is the best possible way to check if additional props appeared\n  //     assert.deepEqual(Object.getOwnPropertyNames(obj), Object.getOwnPropertyNames(new Date()));\n  //   }\n  // }\n  //\n  // \"Plain object in metadata\": {\n  //   topic: function () {\n  //     var obj = { message: \"foo\" };\n  //     fileTransport.log('info', 'test message', obj, this.callback.bind(this, null, obj));\n  //   },\n  //   \"should not be modified\": function (err, obj) {\n  //     assert.deepEqual(obj, { message: \"foo\" });\n  //   }\n  // }\n  //\n  // \"An instance of the File Transport\": require('./transport')(winston.transports.File, {\n  //   filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testfile.log')\n  // })\n});\n\n"
  },
  {
    "path": "test/unit/winston/transports/http.test.js",
    "content": "/*\n * http-test.js: Tests for instances of the HTTP transport\n *\n * MIT LICENSE\n */\n\nconst http = require('http');\nconst hock = require('hock');\nconst assume = require('assume');\nconst Http = require('../../../../lib/winston/transports/http');\nconst stringifyJson = require('safe-stable-stringify');\n\nconst host = '127.0.0.1';\nconst port = 0;\n\nfunction mockHttpServer(done, expectedLog) {\n\n  const mock = hock.createHock();\n  const opts = {\n    path: 'log',\n    payload: expectedLog\n  };\n\n  mock\n    .post('/' + opts.path, opts.payload)\n    .min(1)\n    .max(1)\n    .reply(200);\n\n  var server = http.createServer(mock.handler);\n  server.listen(port, '0.0.0.0', done);\n  return { server, mock };\n}\n\nfunction assumeError(err) {\n  if (err) {\n    assume(err).falsy();\n  }\n}\n\nfunction onLogged(context, done) {\n  context.mock.done(function (err) {\n    assumeError(err);\n    done();\n  });\n}\n\ndescribe('Http({ host, port, path })', function () {\n  let context;\n  let server;\n  const dummyLog = {\n    level: 'info',\n    message: 'hello',\n    meta: {},\n    path: '/error'\n  };\n\n  afterEach(function (done) {\n    server.close(done.bind(null, null));\n  });\n\n  describe('nominal', function () {\n\n    beforeEach(function (done) {\n      context = mockHttpServer(done, dummyLog);\n      server = context.server;\n    });\n\n    it('should send logs over HTTP', function (done) {\n      const httpTransport = new Http({\n        host: host,\n        port: server.address().port,\n        path: 'log'\n      }).on('error', assumeError).on('logged', function () {\n        onLogged(context, done);\n      });\n      httpTransport.log(dummyLog, assumeError);\n    });\n\n  });\n\n  describe('batch mode: max message', function () {\n\n    beforeEach(function (done) {\n      context = mockHttpServer(done, [dummyLog, dummyLog, dummyLog, dummyLog, dummyLog]);\n      server = context.server;\n    });\n\n    it('test max message reached', function (done) {\n      const httpTransport = new Http({\n        host: host,\n        port: server.address().port,\n        path: 'log',\n        batch: true,\n        batchCount: 5\n      })\n        .on('error', assumeError)\n        .on('logged', function () {\n          onLogged(context, done);\n        });\n\n      httpTransport.log(dummyLog, assumeError);\n      httpTransport.log(dummyLog, assumeError);\n      httpTransport.log(dummyLog, assumeError);\n      httpTransport.log(dummyLog, assumeError);\n      httpTransport.log(dummyLog, assumeError);\n    });\n\n  });\n\n  describe('batch mode: timeout', function () {\n\n    beforeEach(function (done) {\n      context = mockHttpServer(done, [dummyLog, dummyLog]);\n      server = context.server;\n    });\n\n    it('test timeout reached', function (done) {\n      jest.setTimeout(5000);\n      const httpTransport = new Http({\n        host: host,\n        port: server.address().port,\n        path: 'log',\n        batch: true,\n        batchCount: 5,\n        batchInterval: 2000\n      })\n        .on('error', assumeError)\n        .on('logged', function () {\n          onLogged(context, done);\n        });\n\n      httpTransport.log(dummyLog, assumeError);\n      httpTransport.log(dummyLog, assumeError);\n    });\n\n  });\n\n  describe('circular structure', function () {\n    const circularLog = {\n      level: 'error',\n      message: 'hello',\n      meta: {}\n    };\n\n    circularLog.self = circularLog;\n\n    beforeEach(function (done) {\n      context = mockHttpServer(done, stringifyJson(circularLog));\n      server = context.server;\n    });\n\n    it('should be able to handle options with circular structure', function (done) {\n      const httpTransport = new Http({\n        host: host,\n        port: server.address().port,\n        path: 'log'\n      })\n        .on('error', assumeError)\n        .on('logged', function () {\n          onLogged(context, done);\n        });\n\n      httpTransport.log(circularLog, assumeError);\n    });\n\n    it('should be able to handle options with circular structure when passing maximumDepth', function (done) {\n      const httpTransport = new Http({\n        host: host,\n        maximumDepth: 5,\n        port: server.address().port,\n        path: 'log'\n      })\n        .on('error', assumeError)\n        .on('logged', function () {\n          onLogged(context, done);\n        });\n\n      httpTransport.log(circularLog, assumeError);\n    });\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/transports/stream.test.js",
    "content": "'use strict';\n\nconst path = require('path');\nconst writeable = require('../../../helpers').writeable;\nconst { MESSAGE } = require('triple-beam');\nconst os = require('os');\nconst winston = require('../../../../lib/winston');\nconst split = require('split2');\nconst assume = require('assume');\n\ndescribe('Stream({ stream })', function () {\n  it('should support objectMode streams', function (done) {\n    const expected = {\n      level: 'info',\n      message: 'lolwut testing!'\n    };\n\n    const stream = writeable(function (info) {\n      assume(info).equals(expected);\n      done();\n    });\n\n    const transport = new winston.transports.Stream({ stream });\n    transport.log(expected);\n  });\n\n  it('should support UTF8 encoding streams', function (done) {\n    const expected = {\n      level: 'info',\n      message: 'lolwut testing!',\n      [MESSAGE]: 'info: lolwut testing!'\n    };\n\n    const stream = writeable(function (raw) {\n      assume(raw.toString()).equals(`${expected[MESSAGE]}${os.EOL}`);\n      done();\n    }, false);\n\n    const transport = new winston.transports.Stream({ stream });\n    transport.log(expected);\n  });\n\n  it('should throw when not passed a stream', function () {\n    assume(function () {\n      const stream = new winston.transports.Stream()\n    }).throws('options.stream is required.');''\n  });\n});\n"
  },
  {
    "path": "test/unit/winston/winston.test.js",
    "content": "/*\n * winston.test.js: Tests for instances of the winston Logger\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENSE\n *\n */\n\nconst assume = require('assume');\nconst winston = require('../../../lib/winston');\n\ndescribe('Winston', function () {\n  it('should expose transports', function () {\n    assume(winston.transports).is.an('object');\n    assume(winston.Transport).is.a('function');\n    assume(!winston.transports.Transport).true();\n    assume(winston.transports.Console).is.a('function');\n    assume(winston.transports.File).is.a('function');\n  });\n\n  it('should have the expected initial state', function () {\n    assume(winston.default.transports).deep.equals([]);\n    assume(winston.level).equals('info');\n  });\n\n  describe('exposed interface', function () {\n    const expectedMethods = [\n      'log',\n      'query',\n      'stream',\n      'add',\n      'remove',\n      'clear',\n      'profile',\n      'startTimer',\n      'handleExceptions',\n      'unhandleExceptions',\n      'handleRejections',\n      'unhandleRejections',\n      'configure',\n      'child',\n      'createLogger'\n    ];\n    it.each(expectedMethods)('should expose a method of \"%s()\"', function (method) {\n      const actualMethod = winston[method];\n      assume(actualMethod).is.a('function', 'winston.' + method);\n    });\n\n    const expectedProperties = [\n      { property: 'level', type: 'string' },\n      { property: 'exceptions', type: 'object' },\n      { property: 'rejections', type: 'object' },\n      { property: 'exitOnError', type: 'boolean' }\n    ];\n    it.each(expectedProperties)('should expose a property of \"$property\"', function ({ property, type }) {\n      const actualProperty = winston[property];\n      assume(actualProperty).is.of.a(type);\n    });\n\n    const expectedLevelMethods = [\n      'error',\n      'warn',\n      'info',\n      'http',\n      'verbose',\n      'debug',\n      'silly'\n    ];\n    it.each(expectedLevelMethods)('should expose a level method of \"%s()\"', function (levelMethod) {\n      const actualLevelMethod = winston[levelMethod];\n      assume(actualLevelMethod).is.a('function', 'winston.' + levelMethod);\n      assume(actualLevelMethod).does.not.throw();\n    });\n\n    it('exposes the configuration', function () {\n      assume(winston.config).is.an('object');\n    });\n\n    it('exposes the version', function () {\n      assume(winston.version).equals(require('../../../package.json').version);\n    });\n  });\n\n\n  describe('Deprecated Winston properties from < v3.x', function () {\n    const deprecatedFunctions = ['addRewriter', 'addFilter', 'cli', 'clone', 'extend'];\n    const deprecatedProperties = ['emitErrs', 'levelLength', 'padLevels', 'stripColors'];\n\n\n    it.each(deprecatedFunctions)('should throw when the deprecated function \"%s()\" is invoked', function (functionName) {\n      const invokeFn = function () {\n        winston[functionName]();\n      };\n      assume(invokeFn).throws();\n    });\n\n    it.each(deprecatedProperties)('should throw when the deprecated property \"%s\" is accessed', function (property) {\n      const accessProperty = function () {\n        winston[property];\n      };\n      assume(accessProperty).throws();\n    });\n  });\n});\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"lib\": [\n      \"es6\"\n    ],\n    \"target\": \"es6\",\n    \"noImplicitAny\": true,\n    \"noImplicitThis\": true,\n    \"strictNullChecks\": true,\n    \"baseUrl\": \"./\",\n    \"typeRoots\": [\n      \"./node_modules/@types\",\n      \"./node_modules\"\n    ],\n    \"types\": [\"node\"],\n    \"noEmit\": true,\n    \"forceConsistentCasingInFileNames\": true\n  },\n  \"files\": [\n    \"index.d.ts\",\n    \"lib/winston/config/index.d.ts\",\n    \"lib/winston/transports/index.d.ts\"\n  ]\n}\n"
  }
]