https://github.com/nyxb/consolji
๐ Easily log console messages in Node.js and the browser with this sleek and sophisticated logger.
https://github.com/nyxb/consolji
beutiful cli console fancy log node terminal
Last synced: about 2 months ago
JSON representation
๐ Easily log console messages in Node.js and the browser with this sleek and sophisticated logger.
- Host: GitHub
- URL: https://github.com/nyxb/consolji
- Owner: nyxb
- License: mit
- Created: 2023-05-05T17:58:36.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2023-06-17T14:32:26.000Z (about 3 years ago)
- Last Synced: 2025-06-23T04:20:25.864Z (about 1 year ago)
- Topics: beutiful, cli, console, fancy, log, node, terminal
- Language: TypeScript
- Homepage: https://nyxb.xyz
- Size: 1.1 MB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
[![cover][cover-src]][cover-href]
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![License][license-src]][license-href]
> ๐งโโ๏ธ Magical Console Wrapper with Conventional๐Commits
## ๐ค Why Consolji?
๐ Consolji's Enchanting Features:
- โจ Effortless to use
- ๐ฉ Captivating output with graceful fallbacks
- ๐ฎ Enchanting reporters to suit your needs
- ๐ป Seamless command line experience
- ๐ท๏ธ Tag support for organized logging
- ๐ Cross-platform compatibility, including browsers
- โฏ๏ธ Pause and resume logging as needed
- ๐ญ Embrace the power of log mocking
- ๐ซ Prevent log spam with sorcery of throttling
- ๐ Intercept and redirect console and stdout/stderr with ease
- ๐ [Full conventional๐Commit support](https://github.com/conventional-emoji-commits)
- ๐ฎ Interactive prompt support with the magic of [tyck](https://github.com/nyxblabs/tyck)
## ๐ป Installation:
Using [nyxi](https://github.com/nyxb/nyxi)
```bash
# nyxi
nyxi consolji
# pnpm
pnpm add consolji
# npm
npm i consolji
# yarn
yarn add consolji
```
## ๐ Getting Started
```ts
// ESM
import { consolji, createConsolji } from 'consolji'
// CommonJS
const { consolji, createConsolji } = require('consolji')
consolji.info('Using consolji 0.0.1')
consolji.start('Building project...')
consolji.warn('๐ฅณ consolji is published: 0.0.1')
consolji.success('Project built!')
consolji.error(new Error('This is an example error. Everything is fine!'))
await consolji.prompt('Deploy to the production?', {
type: 'confirm',
})
```
๐ฅ๏ธ Will display in the terminal:

๐ฆ You can use smaller core builds without fancy reporter to save 80% of the bundle size:
```ts
import { consolji, createconsolji } from 'consolji/basic'
import { consolji, createconsolji } from 'consolji/browser'
import { createconsolji } from 'consolji/core'
```
## ๐ consolji Methods
#### ๐ `(logObject)` ๐ `(args...)`
Log to all reporters.
Example: `consolji.info('Message')`
#### โณ `await prompt(message, { type })`
๐ Show an input prompt. Type can be one of `text`, `confirm`, `select`, or `multiselect`.
See [๐ examples/prompt.ts](./examples/prompt.ts) for usage examples.
#### โ `addReporter(reporter)`
- Aliases: โ `add`
Register a custom reporter instance.
#### โ `removeReporter(reporter?)`
- Aliases: โ `remove`, โ `clear`
Remove a registered reporter.
If no arguments are passed all reporters will be removed.
#### ๐ `setReporters(reporter|reporter[])`
Replace all reporters.
#### ๐ง `create(options)`
Create a new `consolji` instance and inherit all parent options for defaults.
#### ๐ ๏ธ `withDefaults(defaults)`
Create a new `consolji` instance with provided defaults
#### ๐ท๏ธ `withTag(tag)`
- Aliases: ๐ท๏ธ `withScope`
Create a new `consolji` instance with that tag.
#### ๐ `wrapConsole()` โช `restoreConsole()`
Globally redirect all `console.log`, etc calls to consolji handlers.
#### ๐ `wrapStd()` โช `restoreStd()`
Globally redirect all stdout/stderr outputs to consolji.
#### ๐ `wrapAll()` โช `restoreAll()`
Wrap both, std and console.
console uses std in the underlying so calling `wrapStd` redirects console too.
Benefit of this function is that things like `console.info` will be correctly redirected to the corresponding type.
#### โธ๏ธ `pauseLogs()` โถ๏ธ `resumeLogs()`
- Aliases: โธ๏ธ `pause`/โถ๏ธ `resume`
**Globally** โธ๏ธ pause and โถ๏ธ resume logs.
consolji will enqueue all logs when paused and then sends them to the reported when resumed.
#### ๐ `mockTypes`
- Aliases: ๐ `mock`
Mock all types. Useful for using with tests.
The first argument passed to `mockTypes` should be a callback function accepting `(typeName, type)` and returning the mocked value:
```ts
consolji.mockTypes((typeName, type) => jest.fn())
```
Please note that with the example above, everything is mocked independently for each type. If you need one mocked fn create it outside:
```ts
const fn = jest.fn()
consolji.mockTypes(() => fn)
```
If callback function returns a _falsy_ value, that type won't be mocked.
For example if you just need to mock `consolji.fatal`:
```ts
consolji.mockTypes(typeName => typeName === 'fatal' && jest.fn())
```
**NOTE:** Any instance of ๐ consolji that inherits the mocked instance will apply the provided callback again. This way, mocking works for ๐ท๏ธ `withTag` scoped loggers without the need for extra efforts.
## ๐ Custom Reporters
๐ consolji 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 [nyxblabs/envizor](https://github.com/nyxblabs/envizor) and a basic browser reporter.
You can create a new reporter object that implements `{ log(logObject): () => { } }` interface.
**Example:** Simple JSON reporter ๐
```ts
import { createconsolji } from 'consolji'
const consolji = createconsolji({
reporters: [
{
log: (logObj) => {
console.log(JSON.stringify(logObj))
},
},
],
})
// Prints {"date":"2023-04-18T12:43:38.693Z","args":["foo bar"],"type":"log","level":2,"tag":""}
consolji.log('foo bar')
```
## ๐ Log Level
๐ consolji only shows logs with configured log level or below. (Default is `3`)
๐ Available log levels:
- `0`: โ๏ธ Fatal and Error
- `1`: โ ๏ธ Warnings
- `2`: โน๏ธ Normal logs
- `3`: โจ Informational logs, success, fail, ready, start, ...
- `4`: ๐ Debug logs
- `5`: ๐ต๏ธ Trace logs
- `-999`: ๐ Silent
- `+999`: ๐ Verbose logs
๐ You can set the log level by either:
- ๐ ๏ธ Passing `level` option to `createconsolji`
- ๐ Setting `consolji.level` on instance
- ๐ Using the `consolji_LEVEL` environment variable (not supported for browser and core builds).
## ๐ Log Types
Log types are exposed as `consolji.[type](...)` and each is a preset of styles and log level.
A list of all available built-in types is [available here](./src/constants.ts).
## ๐งช Creating a new instance
๐ consolji has a global instance and is recommended to use everywhere.
In case more control is needed, create a new instance.
```ts
import { createconsolji } from 'consolji'
const logger = createconsolji({
// level: 4,
// fancy: true | false
// formatOptions: {
// columns: 80,
// colors: false,
// compact: false,
// date: false,
// },
})
```
## ๐ ๏ธ Integrations
### With ๐ jest or ๐ฑ vitest
```ts
describe('your-consolji-mock-test', () => {
beforeAll(() => {
// Redirect std and console to consolji too
// Calling this once is sufficient
consolji.wrapAll()
})
beforeEach(() => {
// Re-mock consolji before each test call to remove
// calls from before
consolji.mockTypes(() => jest.fn())
})
test('your test', async () => {
// Some code here
// Let's retrieve all messages of `consolji.log`
// Get the mock and map all calls to their first argument
const consoljiMessages = consolji.log.mock.calls.map(c => c[0])
expect(consoljiMessages).toContain('your message')
})
})
```
### With ๐ jsdom
```ts
{
virtualConsole: new jsdom.VirtualConsole().sendTo(consolji)
}
```
## ๐ License
[MIT](./LICENSE) - Made with ๐
[npm-version-src]: https://img.shields.io/npm/v/consolji?style=flat&colorA=18181B&colorB=14F195
[npm-version-href]: https://npmjs.com/package/consolji
[npm-downloads-src]: https://img.shields.io/npm/dm/consolji?style=flat&colorA=18181B&colorB=14F195
[npm-downloads-href]: https://npmjs.com/package/consolji
[bundle-src]: https://img.shields.io/bundlephobia/minzip/consolji?style=flat&colorA=18181B&colorB=14F195
[bundle-href]: https://bundlephobia.com/result?p=consolji
[license-src]: https://img.shields.io/github/license/nyxblabs/consolji.svg?style=flat&colorA=18181B&colorB=14F195
[license-href]: https://github.com/nyxblabs/consolji/blob/main/LICENSE
[cover-src]: https://raw.githubusercontent.com/nyxblabs/consolji/main/.github/assets/cover-github-consolji.png
[cover-href]: https://๐ปnyxb.ws