By Craig Buckler translator: OpenReplay

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.

I now use console.log() to debug my code. It’s a low level debugging method, but it works. Of course, you can use other tools if you get more complicated, but console.log() is pretty much enough for daily development.

Now that we’re done with the prefixes, let’s take a look at some of the other fancy things in console.log().

1. Use ES6 destruct assignment to output variable names

If multiple values are printed, we usually print them with the variable name to distinguish them:

const variableX = 42;
console.log('variableX:', variableX);
/ / or
console.log(`variableX: ${ variableX }`);
Copy the code

In fact, there is a very concise way to use deconstruction:

const variableX = 42;
console.log({ variableX }); // { variableX: 42 }
Copy the code

2. Use the appropriate print type

Console.log () is usually used like this:

console.log('no-frills log message');
Copy the code

But it’s not the only type. Messages can be categorized as information (handled in the same way as console.log()).

console.info('this is an information message');
Copy the code

Warning:

console.warn('I warned you this could happen! ');Copy the code

Error:

console.error('I\'m sorry Dave, I\'m afraid I can\'t do that');
Copy the code

Or less important debugging information:

console.debug('nothing to see here - please move along');
Copy the code

Console.table () can output the object’s value in a more friendly format.

const obj = {
    propA: 1,
    propB: 2,
    propC: 3
  };
console.table( obj );
Copy the code

Or array of objects:

const arr2 = [
    { a: 1, b: 2, c: 3 },
    { a: 4, b: 5, c: 6 },
    { a: 7, b: 8, c: 9 }
  ];

console.table( arr2 );
Copy the code

Other options include:

  • console.dir( obj )Displays a list of interactive properties for a JS object
  • console.dirxml( element )Displays an interactive tree of child elements of the specified HTML or XML node.
  • console.clear()Clear all information up to the console.

3. Filter log messages

The browser displays the log information in the appropriate color, but it can also be filtered to display a specific type. Click on the icon in the upper left of the console pane to open Chrome’s sidebar.

Note that the console.debug() message is only displayed when viewing the verbose option.

Use 4.printf-typeThe information of

All logging types can use the C-style printf message format, which defines a template containing a % indicator where a variable is replaced. For example,

console.log(
  'The answer to %s is %d.',
  'life, the universe and everything',
  42
);
// The answer to life, the universe and everything is 42.
Copy the code

Style with style

console.log( '%cOK, things are really bad now! ', ` font-size: 2em; Padding: 0.5 em 2 em; margin: 1em 0; color: yellow; background-color: red; border-radius: 50%; `);Copy the code

Results in the console:

6. Use assertions like tests

The test-like console.assert() command can be used to output a message if a condition fails. Assertions can be defined with a condition and one or more objects, and output when the condition fails, for example

console.assert(
  life === 42,
  'life is expected to be',
  42,
  'but is set to',
  life
);
Copy the code

Alternatively, you can use an information and replacement value.

console.assert(
  life === 42,
  'life is expected to be %s but is set to %s',
  42,
  life
);
Copy the code

Both options display an assertion error when the condition fails.

7. Run the stack trace

You can use console.trace() to output a log of all function calls that make up the current point of execution.

function callMeTwo() {
  console.trace();
  return true;
}
function callMeOne() {
  return callMeTwo();
}
const r = callMeOne();
Copy the code

The trace shows which line each call is on, and can be collapsed or expanded in the console pane:

8. Group log messages

When printing logs, you can use console.group(label) at the beginning and console.groupend () at the end to divide the log messages into named groups. Message groups can be nested and collapsed or collapsed (console.groupCollapsed(label) initially shows collapsed groups) :

// start log group
console.group('iloop');

for (let i = 3; i > 0; i--) {

  console.log(i);

  // start collapsed log group
  console.groupCollapsed('jloop');

  for (let j = 97; j < 100; j++) {
    console.log(j);
  }

  // end log group (jloop)
  console.groupEnd();

}

// end log group (iloop)
console.groupEnd();
Copy the code

9. Use timers

Console. time and console.timeEnd are two methods that allow WEB developers to measure how long a javascript script takes to execute. As WEB applications become more important and JavaScript performance becomes more important, WEB developers know that some performance testing machine is a must.

The console.time method is used to start counting the time, and the console.timeEnd method is used to stop the timing and output the time when the script is executed.

// Start the timer console.time('testForEach'); // (write some test code) // Stop timing, output time console.timeEnd('testForEach'); / / 4522.303 msCopy the code

In both cases, you can pass in a parameter as the name of the timer, which is used to clear each timer when the code is running in parallel. The call to console.timeEnd immediately outputs the total execution time in milliseconds.

10. Debug and monitor functions by name

The DevTools Sources panel (or the debugger in Firefox) allows you to open a file and set a breakpoint by clicking the line number. Chrome-based browsers also allow you to set breakpoints by typing DEBUG (functionName) in the console, for example:

debug( doSomething );
Copy the code

This function must be available in the global namespace, and the browser will launch the debugger immediately when it is called. You can undebug using undebug(functionName) or reload the page.

Monitor (function), which takes a function name as an argument, such as function a. Each time a is executed, a message is printed to the console containing the name of the function a and the parameters passed during execution.

Unmonitor (function) is used to stop this listening.

11. Find and fix event listeners

The Firefox DevTools Inspector panel displays an Event icon next to any DOM element to which a handler is attached. Click the icon to see the function name, then click the arrow icon on the left to expand the code. Alternatively, the Open in Debugger icon will locate the handler in the Debugger pane so that breakpoints can be set

Chrome’s implementation isn’t as good, but you can view all event listeners by passing a DOM node through the getEventListeners() function. For example, getEventListeners($0) show listeners applied to the DOM node highlighted in the current Elements panel

12. Copy properties to clipboard

The console’s copy() command copies any value to the clipboard. It can be a primitive value, an array, an object, or a DOM node.

When you pass a DOM node, copy() places the HTML for that element and all its children on the clipboard. This is the same as right-clicking on a node and selecting Copy, then selecting Copy the outer HTML.

The copy(document.documentElement) command copies the entire HTML document. This can be pasted into a text editor and embellished to enhance readability.

Over, the method is a lot, oneself choose to use, I am small wisdom, brush bowl go, we next period see ~


The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: blog.openreplay.com/12-ways-to-…

communication

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.