refactor: unify log format with new logger utility (#5994)

Co-authored-by: sebastienlorber <lorber.sebastien@gmail.com>
This commit is contained in:
Joshua Chen 2021-12-21 00:24:59 +08:00 committed by GitHub
parent faef753730
commit 770418f8d2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
66 changed files with 717 additions and 650 deletions

View file

@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const chalk = require('chalk');
// Force coloring the output even in CI
module.exports = new chalk.Instance({level: 3});

View file

@ -0,0 +1,73 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import logger from '../index';
describe('formatters', () => {
test('path', () => {
expect(logger.path('hey')).toMatchInlineSnapshot(`"hey"`);
});
test('id', () => {
expect(logger.name('hey')).toMatchInlineSnapshot(`"hey"`);
});
test('code', () => {
expect(logger.code('hey')).toMatchInlineSnapshot(`"\`hey\`"`);
});
test('subdue', () => {
expect(logger.subdue('hey')).toMatchInlineSnapshot(`"hey"`);
});
});
describe('interpolate', () => {
test('should format text with variables & arrays', () => {
const name = 'Josh';
const items = [1, 'hi', 'Hmmm'];
expect(logger.interpolate`Hello ${name}! Here are your goodies:${items}`)
.toMatchInlineSnapshot(`
"Hello Josh! Here are your goodies:
- 1
- hi
- Hmmm"
`);
});
test('should recognize valid flags', () => {
expect(
logger.interpolate`The package at path=${'packages/docusaurus'} has number=${10} files. name=${'Babel'} is exported here subdue=${'(as a preset)'} that you can with code=${"require.resolve('@docusaurus/core/lib/babel/preset')"}`,
).toMatchInlineSnapshot(
`"The package at packages/docusaurus has 10 files. Babel is exported here (as a preset) that you can with \`require.resolve('@docusaurus/core/lib/babel/preset')\`"`,
);
});
test('should interpolate arrays with flags', () => {
expect(
logger.interpolate`The following commands are available:code=${[
'docusaurus start',
'docusaurus build',
'docusaurus deploy',
]}`,
).toMatchInlineSnapshot(`
"The following commands are available:
- \`docusaurus start\`
- \`docusaurus build\`
- \`docusaurus deploy\`"
`);
});
test('should print detached flags as-is', () => {
expect(
logger.interpolate`You can use placeholders like code= ${'and it will'} be replaced with the succeeding arguments`,
).toMatchInlineSnapshot(
`"You can use placeholders like code= and it will be replaced with the succeeding arguments"`,
);
});
test('should throw with bad flags', () => {
expect(
() =>
logger.interpolate`I mistyped this: cde=${'this code'} and I will be damned`,
).toThrowErrorMatchingInlineSnapshot(
`"Bad Docusaurus logging message. This is likely an internal bug, please report it."`,
);
});
});

View file

@ -0,0 +1,134 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk, {Chalk} from 'chalk';
type InterpolatableValue = string | number | (string | number)[];
const path = (msg: unknown): string => chalk.cyan(chalk.underline(msg));
const name = (msg: unknown): string => chalk.blue(chalk.bold(msg));
const code = (msg: unknown): string => chalk.cyan(`\`${msg}\``);
const subdue: Chalk = chalk.gray;
const num: Chalk = chalk.yellow;
function interpolate(
msgs: TemplateStringsArray,
...values: InterpolatableValue[]
): string {
let res = '';
values.forEach((value, idx) => {
const flag = msgs[idx].match(/[a-z]+=$/);
res += msgs[idx].replace(/[a-z]+=$/, '');
const format = (function () {
if (!flag) {
return (a: string | number) => a;
}
switch (flag[0]) {
case 'path=':
return path;
case 'number=':
return num;
case 'name=':
return name;
case 'subdue=':
return subdue;
case 'code=':
return code;
default:
throw new Error(
'Bad Docusaurus logging message. This is likely an internal bug, please report it.',
);
}
})();
res += Array.isArray(value)
? `\n- ${value.map((v) => format(v)).join('\n- ')}`
: format(value);
});
res += msgs.slice(-1)[0];
return res;
}
function info(msg: unknown): void;
function info(
msg: TemplateStringsArray,
...values: [InterpolatableValue, ...InterpolatableValue[]]
): void;
function info(msg: unknown, ...values: InterpolatableValue[]): void {
console.info(
`${chalk.cyan(chalk.bold('[INFO]'))} ${
values.length === 0
? msg
: interpolate(msg as TemplateStringsArray, ...values)
}`,
);
}
function warn(msg: unknown): void;
function warn(
msg: TemplateStringsArray,
...values: [InterpolatableValue, ...InterpolatableValue[]]
): void;
function warn(msg: unknown, ...values: InterpolatableValue[]): void {
console.warn(
chalk.yellow(
`${chalk.bold('[WARNING]')} ${
values.length === 0
? msg
: interpolate(msg as TemplateStringsArray, ...values)
}`,
),
);
}
function error(msg: unknown): void;
function error(
msg: TemplateStringsArray,
...values: [InterpolatableValue, ...InterpolatableValue[]]
): void;
function error(msg: unknown, ...values: InterpolatableValue[]): void {
console.error(
chalk.red(
`${chalk.bold('[ERROR]')} ${
values.length === 0
? msg
: interpolate(msg as TemplateStringsArray, ...values)
}`,
),
);
}
function success(msg: unknown): void;
function success(
msg: TemplateStringsArray,
...values: [InterpolatableValue, ...InterpolatableValue[]]
): void;
function success(msg: unknown, ...values: InterpolatableValue[]): void {
console.log(
`${chalk.green(chalk.bold('[SUCCESS]'))} ${
values.length === 0
? msg
: interpolate(msg as TemplateStringsArray, ...values)
}`,
);
}
const logger = {
red: chalk.red,
yellow: chalk.yellow,
green: chalk.green,
bold: chalk.bold,
dim: chalk.dim,
path,
name,
code,
subdue,
num,
interpolate,
info,
warn,
error,
success,
};
export default logger;