在调试 node.js 代码时,是否有一种方法可以在 Visual Studio Code(版本1.10.2)的调试控制台中显示颜色(就像在终端中一样)?
在调试 node.js 代码时,是否有一种方法可以在 Visual Studio Code(版本1.10.2)的调试控制台中显示颜色(就像在终端中一样)?
我试图自定义console.debug()
语句的颜色,因为我通常在生产代码中使用console.info()
(及更高级别)语句,而单元测试使用console.debug()
来提供额外的分析信息。
不幸的是,Javascript认为console.info()
和console.debug()
本质上是相同的。只有一些浏览器会抑制console.debug()
。Visual Studio Code也没有提供单独的选项来配置调试级别输出的不同颜色。
然而,SO上对此和其他帖子的几个回答让我找到了这个简单的解决方案,以便以不同的颜色打印console.debug()
语句。
const PURPLE = "\u001b[35m";
const consoleDebugOrig = console.debug;
console.debug = function (...args) {
consoleDebugOrig(PURPLE, ...args, PURPLE);
};
您甚至可以使用此方法将其他类型的格式应用于调试输出,例如缩进或前缀。
console.log("\u001b[1;32m" + 'This is your message!!!' + "\u001b[0m"); //Green message with escape
console.log("\u001b[1;31m" + 'This is your message!!!' + "\u001b[0m"); //Red message with escape
这是我根据这里的答案(以及一些谷歌搜索)编写的一个小实用程序:
export const colored_console = {
/**
* @param color red | green | yellow | blue | purple | cyan | red_bg | green_bg | blue_bg | purple_bg | cyan_bg | yellow_bg | white_bg
* @param args things you want to log
*/
log: function(color, ...args) {
// adjust text color
if (color === 'red' ) { console.log(`\u001b[31m`, ...args, `\u001b[0m`) }
else if (color === 'green' ) { console.log(`\u001b[32m`, ...args, `\u001b[0m`) }
else if (color === 'yellow' ) { console.log(`\u001b[33m`, ...args, `\u001b[0m`) }
else if (color === 'blue' ) { console.log(`\u001b[34m`, ...args, `\u001b[0m`) }
else if (color === 'purple' ) { console.log(`\u001b[35m`, ...args, `\u001b[0m`) }
else if (color === 'cyan' ) { console.log(`\u001b[36m`, ...args, `\u001b[0m`) }
// adjust bg color
else if (color === 'red_bg' ) { console.log(`\u001b[41m`, ...args, `\u001b[0m`) }
else if (color === 'blue_bg' ) { console.log(`\u001b[44m`, ...args, `\u001b[0m`) }
else if (color === 'purple_bg') { console.log(`\u001b[45m`, ...args, `\u001b[0m`) }
else if (color === 'cyan_bg' ) { console.log(`\u001b[46m`, ...args, `\u001b[0m`) }
// adjust text and bg color for better visibility
else if (color === 'green_bg' ) { console.log(`\u001b[42m\u001b[34m`, ...args, `\u001b[0m`) }
else if (color === 'yellow_bg') { console.log(`\u001b[43m\u001b[34m`, ...args, `\u001b[0m`) }
else if (color === 'white_bg' ) { console.log(`\u001b[47m\u001b[34m`, ...args, `\u001b[0m`) }
// if you didn't specify a color, log everything with default color
else { console.log(color, ...args) }
}
}
...这里还有一些我觉得很有用的进一步阅读材料:
Google 搜索:ANSI 颜色(查看图片结果)