Chrome内置的JavaScript控制台可以显示颜色吗?

我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?


当前回答

有一系列内置函数用于为控制台日志上色:

//For pink background and red text
console.error("Hello World");  

//For yellow background and brown text
console.warn("Hello World");  

//For just a INFO symbol at the beginning of the text
console.info("Hello World");  

//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code

//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')

其他回答

下面是另一种方法(在Typescript中),它覆盖console.log函数并检查传递的消息,以便根据消息中的开始标记应用CSS格式。这个方法的一个好处是被调用者不需要使用一些包装console.log函数,他们可以坚持使用普通的console.log(),所以如果这个覆盖消失,该功能将恢复到默认的console.log:

// An example of disabling logging depending on environment:
const isLoggingEnabled = process.env.NODE_ENV !== 'production';

// Store the original logging function so we can trigger it later
const originalConsoleLog = console.log;

// Override logging to perform our own logic
console.log = (args: any) => {
    if (!isLoggingEnabled) {
        return;
    }

    // Define some tokens and their corresponding CSS
    const parsing = [
        {
            token: '[SUCCESS]',
            css: 'color: green; font-weight: bold;',
        },
        {
            token: '[ERROR]',
            css: 'color: red; font-weight: bold;',
        },
        {
            token: '[WARN]',
            css: 'color: orange; font-weight: bold;',
        },
        {
            token: '[DEBUG]',
            css: 'color: blue;',
        },
    ];

    // Currently only supports console.log(...) with a single string argument. 
    if (typeof args === 'string') {
        const message: string = args;
        let formattedArgs: string[] = [];
        for (let i = 0; i < parsing.length; i += 1) {
            const parser = parsing[i];
            if (args.startsWith(parser.token)) {
                formattedArgs = [`%c${message.substring(parser.token.length + 1, message.length)}`, parser.css];
                break;
            }
        }
        originalConsoleLog.apply(console, formattedArgs);
    } else {
        originalConsoleLog.apply(console, args);
    }
};

使用示例:

console.log('[ERROR] Something went wrong!');

输出:

实际上,我只是偶然发现了这个,好奇会发生什么,但你实际上可以使用bash着色标志来设置Chrome输出的颜色:

console.log('\x1b[36m Hello \x1b[34m Colored \x1b[35m World!');
console.log('\x1B[31mHello\x1B[34m World');
console.log('\x1b[43mHighlighted');

输出:

查看这个链接了解颜色标志的工作原理:https://misc.flogisoft.com/bash/tip_colors_and_formatting

基本上用\x1b或\x1b来代替\e。如。\x1b[31m及之后的所有文本将切换为新颜色。

虽然我还没有在其他浏览器中尝试过这个功能,但我认为值得一提。

旧版本的Chrome不允许你让console.log()以编程方式显示特定的颜色,但是调用console.error()会在错误行上放一个红色的X图标,并使文本变成红色,而console.warn()会让你变成黄色!图标。

然后,您可以使用控制台下面的All、Errors、Warnings和Logs按钮筛选控制台条目。


Firebug支持控制台的自定义CSS。从2010年开始,Chrome支持已经添加到Chrome 24。

console.log('%c Oh my heavens! ', 'background: #222; color: #bada55',
            'more text');

当%c出现在第一个参数中的任何位置时,下一个参数将用作设置控制台行样式的CSS。进一步的参数被连接起来(一如既往)。

谷歌对此进行了记录 https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css

CSS格式说明符允许您自定义控制台中的显示。使用说明符开始字符串,并给出希望应用的样式作为第二个参数。

一个例子:

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");

我最近想解决一个类似的问题,构造了一个小函数,只对我关心的关键字进行着色,这些关键字很容易通过周围的花括号{keyword}识别。

这招很管用:

var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
    if (/^\{/.test(split)) {
        cssRules.push('color:blue');
    } else {
        cssRules.push('color:inherit')
    }
    styledText += `%c${split} `
});
console.log(styledText , ...cssRules)

从技术上讲,您可以用switch/case语句替换if语句,以允许根据不同的原因使用多种样式