如何使用console.log省略文件/行号

时间:2016-03-15 10:47:38

标签: javascript browser google-chrome-devtools console.log

在Chrome的控制台中,这些天你可以写出相当不错的东西。结帐this链接。我还制作了截图:

enter image description here

正如您在屏幕截图中看到的那样,文件名/行号(VM298:4)写在右侧。是否有可能删除它,因为在我的情况下,这是一个非常长的名称,或多或少打破了我试图在我的控制台中产生的效果?

4 个答案:

答案 0 :(得分:2)

This is pretty simple to do. You will need to use setTimeout with a console.log.bind:

setTimeout (console.log.bind (console, "This is a sentence."));

And if you want to apply CSS or additional text to it just add add %c or any other % variable:

setTimeout (console.log.bind (console, "%cThis is a sentence.", "font-weight: bold;"));
var css = "text-decoration: underline;";
setTimeout (console.log.bind (console, "%cThis is a sentence.", css));

Note that this method will always be placed at the end of the log list. For example:

console.log ("Log 1");
setTimeout (console.log.bind (console, "This is a sentence."));
console.log ("Log 2");

will appear as

Log 1
Log 2
This is a sentence.

instead of

Log 1
This is a sentence.
Log 2

I hope this answers your question.

答案 1 :(得分:2)

要保持日志记录语句的整洁,您可以定义以下函数,并简单地使用console.print来记录不带文件名/行号的记录:

// console.print: console.log without filename/line number
console.print = function (...args) {
    queueMicrotask (console.log.bind (console, ...args));
}

console.print接受与console.log相同的参数,例如:

console.print("Text with no filename info.")

console.print('%c Custom CSS and no line numbers! ', 'background: #555555; color: #00aaff');

答案 2 :(得分:1)

另一种选择是使用sourceURL

为源脚本文件提供更短的名称
//# sourceURL=new_file_name.js 

答案 3 :(得分:0)

在登录时,将queueMicrotaskconsole.log.bind一起使用可释放源文件信息:

queueMicrotask (console.log.bind (console, "Look! No source file info..."));

如果有多个调用,则排队微任务将保持日志记录的顺序,而不能保证setTimeout按顺序执行任务。