Skip to content

Commit

Permalink
docs: add example usage
Browse files Browse the repository at this point in the history
  • Loading branch information
lukekarrys committed Feb 10, 2022
1 parent 58fd83d commit 33ef65c
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,60 @@ log events that can be consumed by a listener on the process object.
the consumer to stop printing messages.
* `log.resume(...args)` calls `process.emit('log', 'resume', ...args)`
Used to tell the consumer that it is ok to print messages again.
* `log.LEVELS` an array of strings of all log method names

## Examples

Every method calls `process.emit('log', level, ...otherArgs)` internally.
So in order to consume those events you need to do `process.on('log', fn)`.

### Colorize based on level

Here's an example of how to consume `proc-log` events and colorize them
based on level:

```js
const chalk = require('chalk')

process.on('log', (level, ...args) => {
if (level === 'error') {
console.log(chalk.red(level), ...args)
} else {
console.log(chalk.blue(level), ...args)
}
})
```

### Pause and resume

`pause` and `resume` are included so you have the ability to tell your consumer
that you want to pause or resume your display of logs. In the npm CLI we use
this to buffer all logs on init until we know the correct loglevel to display.
But we also setup a second handler that writes everything to a file even if
paused.

```js
let paused = true
const buffer = []

// this handler will buffer and replay logs only
// after `procLog.resume()` is called
process.on('log', (level, ...args) => {
if (level === 'resume') {
buffer.forEach((item) => console.log(...item))
paused = false
return

if (paused) {
buffer.push([level, ...args])
} else {
console.log(level, ...args)
}
})

// this handler will write everything to a file
process.on('log', (...args) => {
fs.appendFileSync('debug.log', args.join(' '))
})
```

0 comments on commit 33ef65c

Please sign in to comment.