/
logToConsole.js
80 lines (71 loc) 路 2.23 KB
/
logToConsole.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
/* eslint-disable no-console */
'use strict';
import type {Terminal} from 'metro-core';
const chalk = require('chalk');
const util = require('util');
const groupStack = [];
let collapsedGuardTimer;
module.exports = (
terminal: Terminal,
level: string,
mode: 'BRIDGE' | 'NOBRIDGE',
...data: Array<mixed>
) => {
const logFunction = console[level] && level !== 'trace' ? level : 'log';
const color =
level === 'error'
? chalk.inverse.red
: level === 'warn'
? chalk.inverse.yellow
: chalk.inverse.white;
if (level === 'group') {
groupStack.push(level);
} else if (level === 'groupCollapsed') {
groupStack.push(level);
clearTimeout(collapsedGuardTimer);
// Inform users that logs get swallowed if they forget to call `groupEnd`.
collapsedGuardTimer = setTimeout(() => {
if (groupStack.includes('groupCollapsed')) {
terminal.log(
chalk.inverse.yellow.bold(' WARN '),
'Expected `console.groupEnd` to be called after `console.groupCollapsed`.',
);
groupStack.length = 0;
}
}, 3000);
return;
} else if (level === 'groupEnd') {
groupStack.pop();
if (!groupStack.length) {
clearTimeout(collapsedGuardTimer);
}
return;
}
if (!groupStack.includes('groupCollapsed')) {
// Remove excess whitespace at the end of a log message, if possible.
const lastItem = data[data.length - 1];
if (typeof lastItem === 'string') {
data[data.length - 1] = lastItem.trimEnd();
}
const modePrefix =
!mode || mode == 'BRIDGE' ? '' : `(${mode.toUpperCase()}) `;
terminal.log(
color.bold(` ${modePrefix}${logFunction.toUpperCase()} `) +
''.padEnd(groupStack.length * 2, ' '),
// `util.format` actually accepts any arguments.
// If the first argument is a string, it tries to format it.
// Otherwise, it just concatenates all arguments.
// $FlowIssue[incompatible-call] util.format expected the first argument to be a string
util.format(...data),
);
}
};