An open API service indexing awesome lists of open source software.

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.

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:

image

๐Ÿ“ฆ 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