From 90ba0de59739f6f0cdebab6b31dacc3625c2208c Mon Sep 17 00:00:00 2001 From: Ray Wang Date: Sun, 16 Jan 2022 14:19:38 +0800 Subject: [PATCH] lib,test,doc: add option to highlight 'warn' and 'error' messages 1. add option to highlight 'warn' and 'error' messages 2. add necessary unit tests 3. update document --- doc/api/console.md | 34 +++++++++ lib/internal/console/constructor.js | 69 +++++++++++++++++-- test/parallel/test-repl.js | 2 +- .../test-console-highlighting-color.js | 53 ++++++++++++++ .../test-console-highlighting-color.out | 17 +++++ .../test-console-highlighting-no-color.js | 22 ++++++ .../test-console-highlighting-no-color.out | 17 +++++ 7 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 test/pseudo-tty/test-console-highlighting-color.js create mode 100644 test/pseudo-tty/test-console-highlighting-color.out create mode 100644 test/pseudo-tty/test-console-highlighting-no-color.js create mode 100644 test/pseudo-tty/test-console-highlighting-no-color.out diff --git a/doc/api/console.md b/doc/api/console.md index 5c8b4ecc64d9b4..831ebd5070db40 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -127,6 +127,19 @@ changes: [`util.inspect()`][]. * `groupIndentation` {number} Set group indentation. **Default:** `2`. + * `highlight` {Object} With this option you can highlight outputs of + [`console.warn()`][] and [`console.error()`][]. It's not enabled by default, + and only affects when coloring is enabled. + * `warn` {Object} Highlight options for [`console.warn()`][]. + * `bgColor` {string} Background color used for highlighting, must be + one of the [`background colors`][] if not omitted. + * `indicator` {string} Optional leading string indicates if the output + is from [`console.warn()`][]. + * `error` {Object} Highlight options for [`console.error()`][]. + * `bgColor` {string} Background color used for highlighting, must be + one of the [`background colors`][] if not omitted. + * `indicator` {string} Optional leading string indicates if the output + is from [`console.error()`][]. Creates a new `Console` with one or two writable stream instances. `stdout` is a writable stream to print log or info output. `stderr` is used for warning or @@ -150,6 +163,25 @@ The global `console` is a special `Console` whose output is sent to new Console({ stdout: process.stdout, stderr: process.stderr }); ``` +You can create your own `Console` with highlighting: + +```js +const logger = new Console({ + stdout: process.stdout, + stderr: process.stderr, + highlight: { + warn: { bgColor: 'bgYellowBright' }, + error: { bgColor: 'bgRedBright', indicator: '\u274c' }, + } +}); + +logger.warn('Warning!'); +// Will output message 'Warning!' along with bright yellow background. +logger.error(new Error('Oops!')); +// Will output message 'Oops!' along with bright red background, +// and a unicode cross sign in front of the message indicating it is an error. +``` + ### `console.assert(value[, ...message])`