{"id":13447084,"url":"https://github.com/unjs/consola","last_synced_at":"2025-05-12T22:33:46.025Z","repository":{"id":38308230,"uuid":"127546642","full_name":"unjs/consola","owner":"unjs","description":"🐨 Elegant Console Logger for Node.js and Browser ","archived":false,"fork":false,"pushed_at":"2025-03-18T11:12:22.000Z","size":2903,"stargazers_count":6605,"open_issues_count":55,"forks_count":199,"subscribers_count":28,"default_branch":"main","last_synced_at":"2025-05-05T17:21:21.601Z","etag":null,"topics":["cli","console","fancy","log","node","terminal"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/unjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-03-31T15:47:47.000Z","updated_at":"2025-05-05T11:30:20.000Z","dependencies_parsed_at":"2023-11-18T03:51:47.786Z","dependency_job_id":"4da0753c-f7de-4c74-b34d-5a9919108c11","html_url":"https://github.com/unjs/consola","commit_stats":{"total_commits":558,"total_committers":53,"mean_commits":"10.528301886792454","dds":0.4623655913978495,"last_synced_commit":"3190635d437f3bb83269b1ec858565ffe44c42a3"},"previous_names":["nuxt/consola"],"tags_count":93,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fconsola","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fconsola/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fconsola/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unjs%2Fconsola/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/unjs","download_url":"https://codeload.github.com/unjs/consola/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252622986,"owners_count":21778139,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","console","fancy","log","node","terminal"],"created_at":"2024-07-31T05:01:07.733Z","updated_at":"2025-05-12T22:33:45.987Z","avatar_url":"https://github.com/unjs.png","language":"TypeScript","readme":"# 🐨 Consola\n\n\u003e Elegant Console Wrapper\n\n[![npm version][npm-version-src]][npm-version-href]\n[![npm downloads][npm-downloads-src]][npm-downloads-href]\n[![bundle][bundle-src]][bundle-href]\n\n\u003c!-- [![Codecov][codecov-src]][codecov-href] --\u003e\n\n## Why Consola?\n\n👌\u0026nbsp; Easy to use\u003cbr\u003e\n💅\u0026nbsp; Fancy output with fallback for minimal environments\u003cbr\u003e\n🔌\u0026nbsp; Pluggable reporters\u003cbr\u003e\n💻\u0026nbsp; Consistent command line interface (CLI) experience\u003cbr\u003e\n🏷\u0026nbsp; Tag support\u003cbr\u003e\n🚏\u0026nbsp; Redirect `console` and `stdout/stderr` to consola and easily restore redirect.\u003cbr\u003e\n🌐\u0026nbsp; Browser support\u003cbr\u003e\n⏯\u0026nbsp; Pause/Resume support\u003cbr\u003e\n👻\u0026nbsp; Mocking support\u003cbr\u003e\n👮‍♂️\u0026nbsp; Spam prevention by throttling logs\u003cbr\u003e\n❯\u0026nbsp; Interactive prompt support powered by [`clack`](https://github.com/natemoo-re/clack)\u003cbr\u003e\n\n## Installation\n\nUsing npm:\n\n```bash\nnpm i consola\n```\n\nUsing yarn:\n\n```bash\nyarn add consola\n```\n\nUsing pnpm:\n\n```bash\npnpm i consola\n```\n\n## Getting Started\n\n```js\n// ESM\nimport { consola, createConsola } from \"consola\";\n\n// CommonJS\nconst { consola, createConsola } = require(\"consola\");\n\nconsola.info(\"Using consola 3.0.0\");\nconsola.start(\"Building project...\");\nconsola.warn(\"A new version of consola is available: 3.0.1\");\nconsola.success(\"Project built!\");\nconsola.error(new Error(\"This is an example error. Everything is fine!\"));\nconsola.box(\"I am a simple box\");\nawait consola.prompt(\"Deploy to the production?\", {\n  type: \"confirm\",\n});\n```\n\nWill display in the terminal:\n\n![consola-screenshot](https://github.com/unjs/consola/assets/904724/0e511ee6-2543-43ab-9eda-152f07134d94)\n\nYou can use smaller core builds without fancy reporter to save 80% of the bundle size:\n\n```ts\nimport { consola, createConsola } from \"consola/basic\";\nimport { consola, createConsola } from \"consola/browser\";\nimport { createConsola } from \"consola/core\";\n```\n\n## Consola Methods\n\n#### `\u003ctype\u003e(logObject)` `\u003ctype\u003e(args...)`\n\nLog to all reporters.\n\nExample: `consola.info('Message')`\n\n#### `await prompt(message, { type, cancel })`\n\nShow an input prompt. Type can either of `text`, `confirm`, `select` or `multiselect`.\n\nIf prompt is canceled by user (with Ctrol+C), default value will be resolved by default. This strategy can be configured by setting `{ cancel: \"...\" }` option:\n\n- `\"default\"` - Resolve the promise with the `default` value or `initial` value.\n- `\"undefined`\" - Resolve the promise with `undefined`.\n- `\"null\"` - Resolve the promise with `null`.\n- `\"symbol\"` - Resolve the promise with a symbol `Symbol.for(\"cancel\")`.\n- `\"reject\"` - Reject the promise with an error.\n\nSee [examples/prompt.ts](./examples/prompt.ts) for usage examples.\n\n#### `addReporter(reporter)`\n\n- Aliases: `add`\n\nRegister a custom reporter instance.\n\n#### `removeReporter(reporter?)`\n\n- Aliases: `remove`, `clear`\n\nRemove a registered reporter.\n\nIf no arguments are passed all reporters will be removed.\n\n#### `setReporters(reporter|reporter[])`\n\nReplace all reporters.\n\n#### `create(options)`\n\nCreate a new `Consola` instance and inherit all parent options for defaults.\n\n#### `withDefaults(defaults)`\n\nCreate a new `Consola` instance with provided defaults\n\n#### `withTag(tag)`\n\n- Aliases: `withScope`\n\nCreate a new `Consola` instance with that tag.\n\n#### `wrapConsole()` `restoreConsole()`\n\nGlobally redirect all `console.log`, etc calls to consola handlers.\n\n#### `wrapStd()` `restoreStd()`\n\nGlobally redirect all stdout/stderr outputs to consola.\n\n#### `wrapAll()` `restoreAll()`\n\nWrap both, std and console.\n\nconsole uses std in the underlying so calling `wrapStd` redirects console too.\nBenefit of this function is that things like `console.info` will be correctly redirected to the corresponding type.\n\n#### `pauseLogs()` `resumeLogs()`\n\n- Aliases: `pause`/`resume`\n\n**Globally** pause and resume logs.\n\nConsola will enqueue all logs when paused and then sends them to the reported when resumed.\n\n#### `mockTypes`\n\n- Aliases: `mock`\n\nMock all types. Useful for using with tests.\n\nThe first argument passed to `mockTypes` should be a callback function accepting `(typeName, type)` and returning the mocked value:\n\n```js\n// Jest\nconsola.mockTypes((typeName, type) =\u003e jest.fn());\n// Vitest\nconsola.mockTypes((typeName, type) =\u003e vi.fn());\n```\n\nPlease note that with the example above, everything is mocked independently for each type. If you need one mocked fn create it outside:\n\n```js\n// Jest\nconst fn = jest.fn();\n// Vitest\nconst fn = vi.fn();\nconsola.mockTypes(() =\u003e fn);\n```\n\nIf callback function returns a _falsy_ value, that type won't be mocked.\n\nFor example if you just need to mock `consola.fatal`:\n\n```js\n// Jest\nconsola.mockTypes((typeName) =\u003e typeName === \"fatal\" \u0026\u0026 jest.fn());\n// Vitest\nconsola.mockTypes((typeName) =\u003e typeName === \"fatal\" \u0026\u0026 vi.fn());\n```\n\n**NOTE:** Any instance of consola that inherits the mocked instance, will apply provided callback again.\nThis way, mocking works for `withTag` scoped loggers without need to extra efforts.\n\n## Custom Reporters\n\nConsola ships with 3 built-in reporters out of the box. A fancy colored reporter by default and fallsback to a basic reporter if running in a testing or CI environment detected using [unjs/std-env](https://github.com/unjs/std-env) and a basic browser reporter.\n\nYou can create a new reporter object that implements `{ log(logObject): () =\u003e { } }` interface.\n\n**Example:** Simple JSON reporter\n\n```ts\nimport { createConsola } from \"consola\";\n\nconst consola = createConsola({\n  reporters: [\n    {\n      log: (logObj) =\u003e {\n        console.log(JSON.stringify(logObj));\n      },\n    },\n  ],\n});\n\n// Prints {\"date\":\"2023-04-18T12:43:38.693Z\",\"args\":[\"foo bar\"],\"type\":\"log\",\"level\":2,\"tag\":\"\"}\nconsola.log(\"foo bar\");\n```\n\n**Example:** Exit on fatal errors\n\n```ts\nimport { consola } from 'consola';\n\nconsola.addReporter({\n  log(logObj) {\n    if(logObj.type === 'fatal') {\n      process.exit(1)\n    }\n  }\n})\n\n// Will exit on this line.\nconsola.fatal(\"fatal error\");\n```\n\n## Log Level\n\nConsola only shows logs with configured log level or below. (Default is `3`)\n\nAvailable log levels:\n\n- `0`: Fatal and Error\n- `1`: Warnings\n- `2`: Normal logs\n- `3`: Informational logs, success, fail, ready, start, ...\n- `4`: Debug logs\n- `5`: Trace logs\n- `-999`: Silent\n- `+999`: Verbose logs\n\nYou can set the log level by either:\n\n- Passing `level` option to `createConsola`\n- Setting `consola.level` on instance\n- Using the `CONSOLA_LEVEL` environment variable (not supported for browser and core builds).\n\n## Log Types\n\nLog types are exposed as `consola.[type](...)` and each is a preset of styles and log level.\n\nA list of all available built-in types is [available here](./src/constants.ts).\n\n## Creating a new instance\n\nConsola has a global instance and is recommended to use everywhere.\nIn case more control is needed, create a new instance.\n\n```js\nimport { createConsola } from \"consola\";\n\nconst logger = createConsola({\n  // level: 4,\n  // fancy: true | false\n  // formatOptions: {\n  //     columns: 80,\n  //     colors: false,\n  //     compact: false,\n  //     date: false,\n  // },\n});\n```\n\n## Integrations\n\n### With jest or vitest\n\n```js\ndescribe(\"your-consola-mock-test\", () =\u003e {\n  beforeAll(() =\u003e {\n    // Redirect std and console to consola too\n    // Calling this once is sufficient\n    consola.wrapAll();\n  });\n\n  beforeEach(() =\u003e {\n    // Re-mock consola before each test call to remove\n    // calls from before\n    // Jest\n    consola.mockTypes(() =\u003e jest.fn());\n    // Vitest\n    consola.mockTypes(() =\u003e vi.fn());\n  });\n\n  test(\"your test\", async () =\u003e {\n    // Some code here\n\n    // Let's retrieve all messages of `consola.log`\n    // Get the mock and map all calls to their first argument\n    const consolaMessages = consola.log.mock.calls.map((c) =\u003e c[0]);\n    expect(consolaMessages).toContain(\"your message\");\n  });\n});\n```\n\n### With jsdom\n\n```js\n{\n  new jsdom.VirtualConsole().sendTo(consola);\n}\n```\n\n## Console Utils\n\n```ts\n// ESM\nimport {\n  stripAnsi,\n  centerAlign,\n  rightAlign,\n  leftAlign,\n  align,\n  box,\n  colors,\n  getColor,\n  colorize,\n} from \"consola/utils\";\n\n// CommonJS\nconst { stripAnsi } = require(\"consola/utils\");\n```\n\n## Raw logging methods\n\nObjects sent to the reporter could lead to unexpected output when object is close to internal object structure containing either `message` or `args` props. To enforce the object to be interpreted as pure object, you can use the `raw` method chained to any log type.\n\n**Example:**\n\n```js\n// Prints \"hello\"\nconsola.log({ message: \"hello\" });\n\n// Prints \"{ message: 'hello' }\"\nconsola.log.raw({ message: \"hello\" });\n```\n\n## License\n\nMIT\n\n\u003c!-- Badges --\u003e\n\n[npm-version-src]: https://img.shields.io/npm/v/consola?style=flat\u0026colorA=18181B\u0026colorB=F0DB4F\n[npm-version-href]: https://npmjs.com/package/consola\n[npm-downloads-src]: https://img.shields.io/npm/dm/consola?style=flat\u0026colorA=18181B\u0026colorB=F0DB4F\n[npm-downloads-href]: https://npmjs.com/package/consola\n[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/consola/main?style=flat\u0026colorA=18181B\u0026colorB=F0DB4F\n[codecov-href]: https://codecov.io/gh/unjs/consola\n[bundle-src]: https://img.shields.io/bundlephobia/min/consola?style=flat\u0026colorA=18181B\u0026colorB=F0DB4F\n[bundle-href]: https://bundlephobia.com/result?p=consola\n","funding_links":[],"categories":["Packages","TypeScript","JavaScript","Projects Using Vue.js","cli","Framework agnostic packages","包"],"sub_categories":["Logging","Open Source","Node","日志"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funjs%2Fconsola","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Funjs%2Fconsola","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funjs%2Fconsola/lists"}