JavaScript控制台中的颜色

1196

Chrome内置的JavaScript控制台能够显示颜色吗?

我希望错误消息以红色显示,警告消息以橙色显示,而console.log中的消息以绿色显示。这可能吗?


71
只需使用console.error()代替console.log,即可在红色(默认)中获得错误提示。请注意,此操作仅为翻译,不包含任何解释或其他信息。 - nrabinowitz
28
console.warn() 也可以使用橙色的“警告”图标,但文本本身仍然是黑色。 - Charlie Schliesser
5
在Chrome浏览器中,特别是在滚动控制台时,console.log("%c", "background: red;padding: 100000px;");会导致非常奇怪的行为。 - user6560716
1
在控制台中显示颜色的最简单的方法是: - Suhaib Janjua
1
我写了一个用于给日志着色的小型软件包:console colors - vsync
30个回答

6

默认情况下,控制台只提供了几种内置的方法用于显示警告、错误和普通信息,并附带特定的图标和文字颜色。

console.log('console.log');
console.warn('console.warn');
console.error('console.error');

但是如果你仍想应用自己的样式,你可以使用%c作为消息的第二个参数,并添加CSS样式规则。

console.log('%cconsole.log', 'color: green;');
console.warn('%cconsole.warn', 'color: green;');
console.error('%cconsole.error', 'color: green;');

注意:在运行上述代码片段时,请务必检查浏览器控制台中的结果,而不是片段结果。

4

选项1

// log-css.js v2
const log = console.log.bind()
const css = (text, options) => {
    let cssOptions = ''
    for (let prop in options) {
        const value = options[prop]
        prop = camelCaseToDashCase(prop)
        cssOptions += `${prop}: ${value}; `
    }
    return [`%c${text}`, cssOptions.trim()]

    function camelCaseToDashCase(value) {
        return value.replace(/[A-Z]/g, matched => `-${matched.toLowerCase()}`)
    }
}

例子:

log(...css('Example =P', {
    backgroundColor: 'blue',
    color: 'white',
    // fontFamily: 'Consolas',
    fontSize: '25px',
    fontWeight: '700',
    // lineHeight: '25px',
    padding: '7px 7px'
}))

选项2

我现在创建了log-css.js文件。 https://codepen.io/luis7lobo9b/pen/QWyobwY

// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
    return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};

例子:

log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));

3

最近我想解决一个类似的问题,构建了一个小函数,只着色我关心的关键词,这些关键词很容易通过花括号{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)

enter image description here

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


3

几年前,我为自己写了一个非常简单的插件:

要将其添加到您的页面中,您只需要将以下内容放置在头部:

<script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript">

然后在JS中:

jconsole.color.red.log('hellllooo world');

该框架包含以下代码:
jconsole.color.red.log();
jconsole.color.orange.log();
jconsole.color.yellow.log();
jconsole.color.green.log();
jconsole.color.blue.log();
jconsole.color.purple.log();
jconsole.color.teal.log();

以及:

jconsole.css.log("hello world","color:red;");

对于任何其他的CSS样式,上述设计采用以下语法:

jconsole.css.log(message to log,css code to style the logged message)

2

这里有另一种方法(使用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!');

输出:

日志的输出


失去调用上下文并显示 apply 发生的行,而不是代码起始行。 - Julian Knight
我看到这是最好的处理控制台日志记录的答案。谢谢。 - Ahmed Sayed Sk

2
我写了一个npm模块,可以让你传递以下内容:
  • 自定义颜色 - 用于文本和背景;
  • 前缀 - 用于标识来源,如[MyFunction]
  • 类型 - 如warningsuccessinfo和其他预定义的消息类型
https://www.npmjs.com/package/console-log-plus 输出结果(带有自定义前缀): enter image description here
clp({
  type: 'ok',
  prefix: 'Okay',
  message: 'you bet'
});
clp({
  type: 'error',
  prefix: 'Ouch',
  message: 'you bet'
});
clp({
  type: 'warning',
  prefix: 'I told you',
  message: 'you bet'
});
clp({
  type: 'attention',
  prefix: 'Watch it!',
  message: 'you bet'
});
clp({
  type: 'success',
  prefix: 'Awesome!',
  message: 'you bet'
});
clp({
  type: 'info',
  prefix: 'FYI',
  message: 'you bet'
});
clp({
  type: 'default',
  prefix: 'No fun',
  message: 'you bet'
});

输出(不带自定义前缀):

输入图像描述

输入

clp({
  type: 'ok',
  message: 'you bet'
});
clp({
  type: 'error',
  message: 'you bet'
});
clp({
  type: 'warning',
  message: 'you bet'
});
clp({
  type: 'attention',
  message: 'you bet'
});
clp({
  type: 'success',
  message: 'you bet'
});
clp({
  type: 'info',
  message: 'you bet'
});
clp({
  type: 'default',
  message: 'you bet'
});

为了确保用户不会渲染无效的颜色,我还编写了一个颜色验证器(validate-color)。它可以通过名称、十六进制、RGB、RGBA、HSL或HSLA值来验证颜色。原始答案翻译成“最初的回答”。

2
我创建了一个相同的软件包。 cslog

screenshow

使用以下命令进行安装:

npm i cslog

像这样使用它。
import log from 'cslog'

log.h2("This is heading 2")
log.p("This is colored paragraph")
log.d(person, "Person Info")

你也可以自定义颜色。详情请点击此处

1

const coloring = fn => ({ background, color = 'white' }) => (...text) => fn(`%c${text.join('')}`, `color:${color};background:${background}`);
const colors = {
  primary: '#007bff',
  success: '#28a745',
  warning: '#ffc107',
  danger: '#dc3545',
  info: '#17a2b8',
};
const dir = (key = '', value = {}) => {
  logs.primary(`++++++++++++start:${key}++++++++++++++`);
  console.dir(value);
  logs.primary(`++++++++++++end:${key}++++++++++++++`);
};
const logs = Object.keys(colors)
  .reduce((prev, curr) => ({ ...prev, [curr]: coloring(console.log)({ background: colors[curr] }) }), { dir });
  
  logs.success('hello succes');
  logs.warning('hello fail');


1

我发现标记控制台日志的简单方法是:

console.log("%c %s", "background-color:yellow; color: black", 'foo');

结果:

enter image description here


-4
如果你想给终端控制台上色,那么你可以使用npm包chalk。
npm i chalk

enter image description here


2
问题是关于浏览器解决方案的。 - WrRaThY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接