在控制台工具中记录消息Log messages in the Console tool

自浏览器开始提供开发人员工具以来, 控制台 一直很常用。Ever since browsers started to offer developer tools, the Console is a favorite. 原因很简单。The reason is simple.

  • 在大多数编程课程,你将学习输出某种打印命令,以深入了解发生的情况。In most programming courses, you learn to output some kind of print command to gain insights about what happens.

在 DevTools 之前,你只能使用 alert()document.write() 语句在浏览器中调试。Before the DevTools, you were limited to an alert() or document.write() statement to debug in the browser.

如果要在控制台中记录 信息,可以使用多种方法。If you want to log information in the Console, lots of methods are available to you. 查看 API 参考中所有 可用的方法Review all of available methods in the API reference. 以下代码段列出了最重要的方法。The following code snippet lists the most important methods.

// prints the text to the console as  a log message
console.log('This is a log message')
// prints the text to the console as an informational message
console.info('This is some information') 
// prints the text to the console as an error message
console.error('This is an error')
// prints the text to the console as a warning
console.warn('This is a warning') 

复制并粘贴控制台中的上一个代码**** 段或导航到控制台消息示例:日志、信息、错误和警告Copy and paste the previous code snippet in the Console or navigate to Console messages examples: log, info, error, and warn. 在控制台中尝试任何方法时****,和 方法似乎执行相同的操作,而 和 方法在消息旁边显示图标以及检查消息堆栈跟踪 log() info() error() warn() 的方法。 When you try any method in the Console, the log() and info() methods seem to do the same thing, while the error() and warn() methods display an icon next to the message and a way to inspect the stack trace of the message.

控制台显示来自不同日志 API 的消息

但是,对于不同的日志任务,仍建议使用 和 ,因为这样可以在控制台 中 info() log() 使用类型 进行筛选It is, however, still a good idea to use info() and log() for different log tasks as that allows you to filter using type in the Console.

不同类型的日志Different types of logs

你可以向控制台发送任何有效的 JavaScript 或 DOM 引用,而不是日志 文本Instead of log text you may send any valid JavaScript or DOM references to the Console. 控制台 美观,它确定发送它的类型。The Console is elegant and it determines the type that you send it. 然后,它为你提供可能的最佳表示形式。It then gives you the best possible representation. 复制并粘贴控制台中的以下代码 段或显示 结果,导航到控制台 消息示例:记录不同类型的Copy and paste the following code snippet in the Console or to display the results, navigate to Console messages examples: logging different types.

let x = 2;
// logs the value of x
// logs the name x and value of x
// logs a DOM reference  
// logs an Object
console.log({"type":"life", "meaning": 42});
let w3techs = ['HTML', 'CSS', 'SVG', 'MathML'];
// logs an Array

每个结果以不同方式显示。Each result is displayed in a different way. 使用三角形切换信息并更详细地分析每个信息。Use the triangles to toggle the information and analyze each one in more detail. 变量周围的大括号字符是避免出现很多日志消息的一个好技巧,其中仅获取值,但不知道该值 {} x 源自何处。The curly brace characters {} around the x variable are a nice little trick to avoid lots of log messages where you only get a value but you don't know where it originated.

使用说明符设置值的格式和转换值Format and convert values with specifiers

所有日志方法的一个特殊功能是,您可以在日志消息中使用说明符。A special feature of all the log methods is that you may use specifiers in your log message. 说明符是日志消息的一部分,以百分比符号 \ () 字符开始,并允许您以不同格式记录特定值, % 甚至转换每个值。Specifiers are part of a log message and start with a percentage sign (%) character and allow you to log certain values in different formats and even convert each.

  • %s 日志为字符串logs as Strings
  • %i %d 日志为 Integersor %d logs as Integers
  • %f 日志作为浮点值logs as a floating-point value
  • %o 日志作为可展开的 DOM 元素logs as an expandable DOM element
  • %O 日志作为可展开的 JavaScript 对象logs as an expandable JavaScript object
  • %c 允许您使用 CSS 设置邮件样式allows you to style you message with CSS
// logs "10x console developer"
console.log('%ix %s developer', 10, 'console');
// logs PI => 3.141592653589793
// logs PI as an integer = 3
console.log('%i', Math.PI); 
// logs the webpage body as a DOM node
console.log('%o', document.body); 
// logs the body of the webpage as a JavaScript object with all properties
console.log('%O', document.body); 
// Displays the message as red and big
console.log('%cImportant message follows','color:red;font-size:40px');

第一个示例显示,说明符的替换顺序是字符串后的参数顺序。The first example displays that the order of replacement of specifiers is the parameter order following the string. 若要显示结果,请复制并粘贴控制台中的上一个代码**** 段或导航到控制台消息示例:使用说明符记录To display the results, copy and paste the previous code snippet in the Console or navigate to Console messages examples: Logging with specifiers. 展开日志中的信息以显示 和 之间的巨大 %o 差异 %OExpand the information in the log to display the huge difference between %o and %O.

组日志消息Group log messages

如果记录许多信息,可以使用 和 方法在控制台 中将日志消息显示为可展开 group groupCollapsed 和可折叠 的组If you log much information, you may use the group and groupCollapsed methods to display log messages as expandable and collapsible groups in the Console. 可以嵌套和命名组,使数据更易于理解。Groups may be nested and named to make the data much easier to understand.

console.group("Passengers: Heart of Gold");
console.log('(Frankie & Benjy)');
console.groupEnd("Passengers: Heart of Gold");

let technologies = {
  "Standards": ["HTML", "CSS", "SVG", "ECMAScript"],
  "Others": ["jQuery", "Markdown", "Textile", "Sass", "Pug"]
for (tech in technologies) {
  technologies[tech].forEach(t => console.log(t));

此外,第二个示例还可以选择生成组名称。Also in the second example, the group names may be optionally generated. 若要显示结果,请复制并粘贴控制台中的上一个代码**** 段或导航到控制台消息示例:对日志进行分组To display the results, copy and paste the previous code snippet in the Console or navigate to Console messages examples: grouping logs. 可以展开和折叠每个部分。You may expand and collapse each of the sections.

将复杂数据显示为表Display complex data as tables

该方法不会将复杂数据记录为可折叠和可展开的对象,而是记录为可以使用不同标题 console.table() 进行排序的表。The console.table() method logs complex data not as a collapsible and expandable object, but as a table that you may sort using different headers. 排序表使用户更容易查看信息。A sorted table makes it much easier for people to review the information. 若要在示例中显示它,请导航到控制台 消息示例:使用表To display it in an example, navigate to Console messages examples: Using table.

let technologies = {
  "Standards": ["HTML", "CSS", "SVG", "ECMAScript"],
  "Others": ["jQuery", "Markdown", "Textile", "Sass", "Pug"]
// log technologies as an object
// display technologies as a table

// get the dimensions of the webpage body
let bodyDimensions = document.body.getBoundingClientRect();
// display dimensions as an object
// display dimensions as a table

使用 console.table 显示数据,使其更易于阅读

的输出 console.table 不仅具有显示在控制台 中的表 格式The output of console.table has a table format not only when it displays in the Console. 例如,如果将表格复制并粘贴到 Excel、Word 或其他支持表格数据的产品中,则结构保持不变。For example, if you copy and paste a table into Excel, Word, or any other product that supports tabular data, the structure remains intact.

如果数据具有命名参数,则该方法还允许您为每个属性指定一个列,以 console.table() Array 作为第二个参数显示。If the data has named parameters, the console.table() method also allows you to specify an Array of columns for each property to display as a second parameter. 以下示例显示如何指定一个可读的列数组。The following example displays how to specify an array of columns that is more readable.

// get all the h1, p and script elements 
let contentElements = document.querySelectorAll(':is(h1,p,script)');
// display the elements as an unfiltered table 
// display only relevant columns 
console.table(contentElements,['nodeName', 'innerText', 'offsetHeight'])

console.table 显示并提供要显示为第二个参数的属性数组的筛选器信息

您可能会尝试将日志方法用作调试网页的主要方式,因为日志方法易于使用。You may be tempted to use the log methods as your main means to debug webpages, because log methods are simple to use. 请考虑任何请求 console.log() 的结果。Consider the result of any console.log() request. Live 产品不应使用用于调试的任何日志。Live products shouldn't use any log that was used to debug. 它可能会向用户显示内部信息。It may reveal inside information to people. 控制台中创建的噪音 非常 强烈。And the noise created in the Console is overwhelming. 当您使用 断点调试Live Expressions时,您可能会发现您的工作流更有效,并且您获得更好的结果。When you use Breakpoint Debugging or Live Expressions, you may find that your workflows are more effective and you get better results.

联系 Microsoft Edge DevTools 团队Getting in touch with the Microsoft Edge DevTools team

使用以下选项讨论帖子中的新功能和更改,或与 DevTools 相关的任何其他内容。Use the following options to discuss the new features and changes in the post, or anything else related to DevTools.

  • 使用“发送反馈”图标发送反馈,或在 DevTools 中选择Alt+Shift+I \ (Windows、Linux) 或 Option+Shift+I \ (macOS)。Send your feedback using the Send Feedback icon or select Alt+Shift+I (Windows, Linux) or Option+Shift+I (macOS) in DevTools.
  • 发推 @EdgeDevToolsTweet at @EdgeDevTools.
  • 我们想要的 Web 提交建议。Submit a suggestion to The Web We Want.
  • 若要提交有关本文的错误,请使用以下“反馈” 部分。To file bugs about this article, use the following Feedback section.

Microsoft Edge DevTools 中的“发送反馈”图标