UNPKG

7.87 kBMarkdownView Raw
1# 🐨 Consola
2
3> Elegant Console Wrapper
4
5[![npm version][npm-version-src]][npm-version-href]
6[![npm downloads][npm-downloads-src]][npm-downloads-href]
7[![bundle][bundle-src]][bundle-href]
8
9<!-- [![Codecov][codecov-src]][codecov-href] -->
10
11## Why Consola?
12
13👌&nbsp; Easy to use<br>
14💅&nbsp; Fancy output with fallback for minimal environments<br>
15🔌&nbsp; Pluggable reporters<br>
16💻&nbsp; Consistent command line interface (CLI) experience<br>
17🏷&nbsp; Tag support<br>
18🚏&nbsp; Redirect `console` and `stdout/stderr` to consola and easily restore redirect.<br>
19🌐&nbsp; Browser support<br>
20⏯&nbsp; Pause/Resume support<br>
21👻&nbsp; Mocking support<br>
22👮‍♂️&nbsp; Spam prevention by throttling logs<br>
23❯&nbsp; Interactive prompt support powered by [`clack`](https://github.com/natemoo-re/clack)<br>
24
25## Installation
26
27Using npm:
28
29```bash
30npm i consola
31```
32
33Using yarn:
34
35```bash
36yarn add consola
37```
38
39Using pnpm:
40
41```bash
42pnpm i consola
43```
44
45## Getting Started
46
47```js
48// ESM
49import { consola, createConsola } from "consola";
50
51// CommonJS
52const { consola, createConsola } = require("consola");
53
54consola.info("Using consola 3.0.0");
55consola.start("Building project...");
56consola.warn("A new version of consola is available: 3.0.1");
57consola.success("Project built!");
58consola.error(new Error("This is an example error. Everything is fine!"));
59consola.box("I am a simple box");
60await consola.prompt("Deploy to the production?", {
61 type: "confirm",
62});
63```
64
65Will display in the terminal:
66
67<img width="760" alt="image" src="https://user-images.githubusercontent.com/5158436/231029244-abc79f48-ca16-4eaa-b592-7abd271ecb1f.png">
68
69You can use smaller core builds without fancy reporter to save 80% of the bundle size:
70
71```ts
72import { consola, createConsola } from "consola/basic";
73import { consola, createConsola } from "consola/browser";
74import { createConsola } from "consola/core";
75```
76
77## Consola Methods
78
79#### `<type>(logObject)` `<type>(args...)`
80
81Log to all reporters.
82
83Example: `consola.info('Message')`
84
85#### `await prompt(message, { type })`
86
87Show an input prompt. Type can either of `text`, `confirm`, `select` or `multiselect`.
88
89See [examples/prompt.ts](./examples/prompt.ts) for usage examples.
90
91#### `addReporter(reporter)`
92
93- Aliases: `add`
94
95Register a custom reporter instance.
96
97#### `removeReporter(reporter?)`
98
99- Aliases: `remove`, `clear`
100
101Remove a registered reporter.
102
103If no arguments are passed all reporters will be removed.
104
105#### `setReporters(reporter|reporter[])`
106
107Replace all reporters.
108
109#### `create(options)`
110
111Create a new `Consola` instance and inherit all parent options for defaults.
112
113#### `withDefaults(defaults)`
114
115Create a new `Consola` instance with provided defaults
116
117#### `withTag(tag)`
118
119- Aliases: `withScope`
120
121Create a new `Consola` instance with that tag.
122
123#### `wrapConsole()` `restoreConsole()`
124
125Globally redirect all `console.log`, etc calls to consola handlers.
126
127#### `wrapStd()` `restoreStd()`
128
129Globally redirect all stdout/stderr outputs to consola.
130
131#### `wrapAll()` `restoreAll()`
132
133Wrap both, std and console.
134
135console uses std in the underlying so calling `wrapStd` redirects console too.
136Benefit of this function is that things like `console.info` will be correctly redirected to the corresponding type.
137
138#### `pauseLogs()` `resumeLogs()`
139
140- Aliases: `pause`/`resume`
141
142**Globally** pause and resume logs.
143
144Consola will enqueue all logs when paused and then sends them to the reported when resumed.
145
146#### `mockTypes`
147
148- Aliases: `mock`
149
150Mock all types. Useful for using with tests.
151
152The first argument passed to `mockTypes` should be a callback function accepting `(typeName, type)` and returning the mocked value:
153
154```js
155consola.mockTypes((typeName, type) => jest.fn());
156```
157
158Please note that with the example above, everything is mocked independently for each type. If you need one mocked fn create it outside:
159
160```js
161const fn = jest.fn();
162consola.mockTypes(() => fn);
163```
164
165If callback function returns a _falsy_ value, that type won't be mocked.
166
167For example if you just need to mock `consola.fatal`:
168
169```js
170consola.mockTypes((typeName) => typeName === "fatal" && jest.fn());
171```
172
173**NOTE:** Any instance of consola that inherits the mocked instance, will apply provided callback again.
174This way, mocking works for `withTag` scoped loggers without need to extra efforts.
175
176## Custom Reporters
177
178Consola 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.
179
180You can create a new reporter object that implements `{ log(logObject): () => { } }` interface.
181
182**Example:** Simple JSON reporter
183
184```ts
185import { createConsola } from "consola";
186
187const consola = createConsola({
188 reporters: [
189 {
190 log: (logObj) => {
191 console.log(JSON.stringify(logObj));
192 },
193 },
194 ],
195});
196
197// Prints {"date":"2023-04-18T12:43:38.693Z","args":["foo bar"],"type":"log","level":2,"tag":""}
198consola.log("foo bar");
199```
200
201## Log Level
202
203Consola only shows logs with configured log level or below. (Default is `3`)
204
205Available log levels:
206
207- `0`: Fatal and Error
208- `1`: Warnings
209- `2`: Normal logs
210- `3`: Informational logs, success, fail, ready, start, ...
211- `4`: Debug logs
212- `5`: Trace logs
213- `-999`: Silent
214- `+999`: Verbose logs
215
216You can set the log level by either:
217
218- Passing `level` option to `createConsola`
219- Setting `consola.level` on instance
220- Using the `CONSOLA_LEVEL` environment variable (not supported for browser and core builds).
221
222## Log Types
223
224Log types are exposed as `consola.[type](...)` and each is a preset of styles and log level.
225
226A list of all available built-in types is [available here](./src/constants.ts).
227
228## Creating a new instance
229
230Consola has a global instance and is recommended to use everywhere.
231In case more control is needed, create a new instance.
232
233```js
234import { createConsola } from "consola";
235
236const logger = createConsola({
237 // level: 4,
238 // fancy: true | false
239 // formatOptions: {
240 // columns: 80,
241 // colors: false,
242 // compact: false,
243 // date: false,
244 // },
245});
246```
247
248## Integrations
249
250### With jest or vitest
251
252```js
253describe("your-consola-mock-test", () => {
254 beforeAll(() => {
255 // Redirect std and console to consola too
256 // Calling this once is sufficient
257 consola.wrapAll();
258 });
259
260 beforeEach(() => {
261 // Re-mock consola before each test call to remove
262 // calls from before
263 consola.mockTypes(() => jest.fn());
264 });
265
266 test("your test", async () => {
267 // Some code here
268
269 // Let's retrieve all messages of `consola.log`
270 // Get the mock and map all calls to their first argument
271 const consolaMessages = consola.log.mock.calls.map((c) => c[0]);
272 expect(consolaMessages).toContain("your message");
273 });
274});
275```
276
277### With jsdom
278
279```js
280{
281 virtualConsole: new jsdom.VirtualConsole().sendTo(consola);
282}
283```
284
285## Console Utils
286
287```ts
288// ESM
289import {
290 stripAnsi,
291 centerAlign,
292 rightAlign,
293 leftAlign,
294 align,
295 box,
296 colors,
297 getColor,
298 colorize,
299} from "consola/utils";
300
301// CommonJS
302const { stripAnsi } = require("consola/utils");
303```
304
305## License
306
307MIT
308
309<!-- Badges -->
310
311[npm-version-src]: https://img.shields.io/npm/v/consola?style=flat&colorA=18181B&colorB=F0DB4F
312[npm-version-href]: https://npmjs.com/package/consola
313[npm-downloads-src]: https://img.shields.io/npm/dm/consola?style=flat&colorA=18181B&colorB=F0DB4F
314[npm-downloads-href]: https://npmjs.com/package/consola
315[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/consola/main?style=flat&colorA=18181B&colorB=F0DB4F
316[codecov-href]: https://codecov.io/gh/unjs/consola
317[bundle-src]: https://img.shields.io/bundlephobia/min/consola?style=flat&colorA=18181B&colorB=F0DB4F
318[bundle-href]: https://bundlephobia.com/result?p=consola