Chrome内置的JavaScript控制台能够显示颜色吗?
我希望错误消息以红色显示,警告消息以橙色显示,而console.log
中的消息以绿色显示。这可能吗?
Chrome内置的JavaScript控制台能够显示颜色吗?
我希望错误消息以红色显示,警告消息以橙色显示,而console.log
中的消息以绿色显示。这可能吗?
默认情况下,控制台只提供了几种内置的方法用于显示警告、错误和普通信息,并附带特定的图标和文字颜色。
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;');
选项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'));
最近我想解决一个类似的问题,构建了一个小函数,只着色我关心的关键词,这些关键词很容易通过花括号{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语句,以允许为不同原因提供多种样式。
几年前,我为自己写了一个非常简单的插件:
要将其添加到您的页面中,您只需要将以下内容放置在头部:
<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)
这里有另一种方法(使用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!');
输出:
[MyFunction]
warning
、success
、info
和其他预定义的消息类型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'
});
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');
console.error()
代替console.log
,即可在红色(默认)中获得错误提示。请注意,此操作仅为翻译,不包含任何解释或其他信息。 - nrabinowitzconsole.warn()
也可以使用橙色的“警告”图标,但文本本身仍然是黑色。 - Charlie Schliesserconsole.log("%c", "background: red;padding: 100000px;");
会导致非常奇怪的行为。 - user6560716