From 33ef65c4dc3cdba2a2555ec1c32f6bd5d281ff6a Mon Sep 17 00:00:00 2001 From: Luke Karrys Date: Thu, 10 Feb 2022 11:47:50 -0700 Subject: [PATCH] docs: add example usage --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/README.md b/README.md index cddbf70..97bb5c0 100644 --- a/README.md +++ b/README.md @@ -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(' ')) +}) +``` \ No newline at end of file