loading...
Cover image for Better console.logs

Better console.logs

wangonya profile image Kinyanjui Wangonya ・2 min read

If you work with javascript a lot, you probably often need to use console.log() to output some info as you go along.

It's usually just the plain old way though:

(() => {
    // do stuff
    console.log('Success!')
})()

plain

Here are a few ways you could make your logs a bit more visually informative, and interesting 🙂

Use console.error() for error logs

(() => {
    // do stuff
    console.error('Oops, something went wrong!')
})()

errorlog

Use console.warn() for warning logs

(() => {
    // do stuff
    console.warn('Warning! Something doesnt seem right.')
})()

warninglog

[Edit] Use console.table() for iterable objects

Thanks to @shoupn and @squgeim for pointing this out in the comments :)

function Person(firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}

const me = new Person('John', 'Smith')

console.table(me)

tablelog

Add your custom styles

(() => {
    // do stuff
    console.log('%c%s',
            'color: green; background: yellow; font-size: 24px;','Success!')
})()

custom_success

You can have a custom function in your code that lets you use "your own" log with colors directly

function customLog(message, color='black') {
     switch (color) {
         case 'success':  
              color = 'Green'
              break
         case 'info':     
                 color = 'Blue'  
              break;
         case 'error':   
              color = 'Red'   
              break;
         case 'warning':  
              color = 'Orange' 
              break;
         default: 
              color = color
     }

     console.log(`%c${message}`, `color:${color}`)
}

customLog('Hello World!')
customLog('Success!', 'success')
customLog('Error!', 'error')
customLog('Warning!', 'warning')
customLog('Info...', 'info')

custom_function

Here's the pen.

Hope you found this useful and happy debugging! 😊

Discussion

pic
Editor guide
Collapse
miku86 profile image
miku86

Related to console.log in the Dev Tools,

we can use $ instead of document.querySelector
and $$ instead of document.querySelectorAll.

That's not related to the jQuery $.

Example:

// old
document.querySelectorAll(".myClass");

// new
$$(".myClass");
Collapse
wangonya profile image
Kinyanjui Wangonya Author

Wow, didn't know that. Thanks!

Collapse
c24w profile image
Chris Watson

Also, $0 to get the element you've got selected in the inspector (in Chrome).

Collapse
gmartigny profile image
Guillaume Martigny

I like to use console.time and console.timeEnd to benchmark code execution time.

console.time("for");

let sum = 0;
for (let i = 0; i < 1e4; ++i) {
  sum += i;
}

console.log(sum);
console.timeEnd("for");

console.time("while");

sum = 0;
let i = 1e4;
while(--i) {
  sum += i;
}

console.log(sum);
console.timeEnd("while");

Collapse
jmscavaleiro profile image
jmscavaleiro

Very useful. Should also be included to the article.

Collapse
link2twenty profile image
Andrew Bone

With your code, you can actually have it change the console type too, like so

function customLog(message, color='black') {
     let logType = 'log';
     switch (color) {
         case 'success':  
              color = 'Green';
              break
         case 'info':     
              color = 'Blue';
              logType = 'info';
              break;
         case 'error':   
              color = 'Red'; 
              logType = 'error';
              break;
         case 'warning':  
              color = 'Orange';
              logType = 'warning';
              break;
         default: 
              color = color
     }

     console[logType](`%c${message}`, `color:${color}`);
}

customLog('Hello World!')
customLog('Success!', 'success')
customLog('Error!', 'error')
customLog('Warning!', 'warning')
customLog('Info...', 'info')

Also, console.count('nameToCount') will count how many times it is called, which can be handy.

Collapse
tetri profile image
Tetri Mesquita

All this methods to debug operations could be seen by final users when console is open in released applications.

I use console.debug with all included arguments and the debug messages only appears when application is in debug mode and the level of messages from console includes Verbose messages.

Collapse
david_j_eddy profile image
David J Eddy

While I do agree using console.log() would present information to the user via the client console once the code has reached the client, it's all accessible anyways. Security through obscurity is not security. Adding breakpoints and tracing code execution in the client is trivial now days.

Collapse
wangonya profile image
Kinyanjui Wangonya Author

Hey Tetri. You're right. These methods are just used in development for debugging and should be omitted in production code to avoid maybe giving out information that shouldn't get to the end user. I should have mentioned that.

Your method is definitely better :)

Collapse
wolfhoundjesse profile image
Jesse M. Holmes

I wasn't sure where to stick this comment. One of my favorite things to do when I visit a new tech website is to check the developer console for hidden messages. Looking at you, Reddit.

Thread Thread
wangonya profile image
Kinyanjui Wangonya Author

Nice idea! I'm actually working on a redesign of my site. I'll make sure to add something fun in the console for anyone looking around :)

Thread Thread
dirtycode1337 profile image
Dirty-Co.de

I do this all the time when surfing through the web, open console, viewing source code, finding curious things - like job offers - which seems to be one of the best placement for web development job offers :). I made a small (totally incomplete) article series (in German) out of it: dirty-co.de/category/jobanzeigen-i... ;)

Collapse
aghost7 profile image
Jonathan Boudreau

I'm a big fan of the debug module. For debug logs that you don't remove afterwards it is very nice.

Another nice thing is console.trace, which also prints out a stack trace where the log is called. Useful if you're trying to debug a function which is being called in several critical areas.

Collapse
nblackburn profile image
Nathaniel Blackburn

I have gone about this via namespacing my debug logs so it assigns a colour based on that namespace.

debug('cache:set', {}) // cache:set +1ms {}

The namespace here being cache which is mapped against an array of colours using the following code...

let log = 'cache:set';
let colors = [];

const hash = data => {
    let hash = 0;

    for (let index = 0; index < data.length; index++) {
        hash = ((hash << 5) + hash + data.charCodeAt(index)) & 0xffffffff;
    }

    return hash;
};

let namespace = log.substring(0, log.indexOf(':'));
let color = colors[Math.abs(hash(namespace)) % colors.length];

This way cache logs are always shown in the same colour allowing you to visually identify them.

Collapse
gypsydave5 profile image
David Wickes

That's great - I didn't know about console.table. That's some very cool web-fu.

BUT!

Remember - all this debugging is as nothing to the power of good automated tests. A debug line should be ephemeral - an automated test is for life!

Collapse
julesmanson profile image
jules manson

As a temporary measure for writing quicker console.log()'s just put the following in a temporary file (for polluting the global namespace) and link it to the top of your web application then unlink it when no longer needed:

const log = (...args) => console.log(...args);

Now you can easily do...

log(message, ' : ', func.name, func(arg));

Error at nameOfFunc : undefined // example output

This is especially useful when logging multiple test cases in a single run. Similarly can be done with the other console methods. And if you really want to go crazy, this can also be done with Object.prototype.methods but you must often bind the function to the calling object's scope by setting the context with Function.prototype.bind or Function.prototype.call. I think ES5 and ES6 have made Function.prototype.apply obsolete so I don't use it or recommend it anymore. But only do this on very small projects or inside created objects.

Collapse
tedhagos profile image
Ted Hagos

You can also take a look at chalk for coloring the terminal string

Collapse
thomasbnt profile image
Thomas Bnt

Nice for adding colors on console. It's better!

Collapse
wangonya profile image
Kinyanjui Wangonya Author

Yeah! Hope you'll try it out on your next project :)

Collapse
thomasbnt profile image
Thomas Bnt

It's already done ! I've seen this before, but your article complements this feature.

Collapse
lmbarr profile image
Luis Miguel

I use console.trace to check the stack calls. I use also console.log({variableName}) to get the variableName in the console..

Collapse
bengreenberg profile image
Ben Greenberg

Is there anything more fun than inspecting a website you're visiting for hidden console.log messages? The console.table is a new one for me and it's awesome, thanks for sharing!

Collapse
wangonya profile image
Kinyanjui Wangonya Author

Now I feel like its the first thing I'll be doing whenever I access a tech related website 😅

Collapse
bengreenberg profile image
Ben Greenberg

Not just tech sites... I've seen some great ones on other sites too, kinda like those easter eggs in old video games.

Another good thing to look for is to inspect a site with Redux devtools and watch all the state change.

Collapse
squgeim profile image
Shreya Dahal

console.table also comes in handy a lot.

Collapse
wangonya profile image
Kinyanjui Wangonya Author

Ah, yes! I'll edit the post and add in that section for future readers when I find some time. Thanks!

Collapse
shoupn profile image
Nick Shoup

Nice. For iterable objects look into console.table()

Collapse
jmscavaleiro profile image
jmscavaleiro

Short, simple and easy! Thanks!

Collapse
robustdj profile image
Derrick Camerino

Cool! Didn't know about the styling/coloring

Collapse
wangonya profile image
Kinyanjui Wangonya Author

Glad you learnt something :)

Collapse
nssimeonov profile image
Templar++

Idea: Make this an npm package. Wait for it to become popular enough. Inject code to steal credit cards :)

(There was an article about this a few months ago, luckily it was a joke)

Collapse
enriquemorenotent profile image
Collapse
jess profile image
Jess Lee (she/her)

ah cool, i did not know about error or warn!

Collapse
wangonya profile image
Kinyanjui Wangonya Author

Glad I could help :)

Collapse
burzumumbra profile image
Ronald Flores Sequeira

I thought that console.pretty was a fast way to do this, now I'll star to use more the manual way of console.*

bvaughn / console.pretty

Pretty console logging

console.pretty

artist palette

Pretty console logging.



version MIT License styled with prettier

The problem

You're trying to log information, but have a hard time tracking down what the output means, where it came from, or can't find what you're looking for quickly.

This solution

Use colors to easily parse through your console.

Example

import log, { green } from "console.pretty"
const handleOnClick = () => {
  log.blue("Click!")
}
const handleMouseover = () => {
  green("Mouseover!");
};

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

$ npm install console.pretty

or

$ yarn add console.pretty

API

By default, the following colors are available:

  • blue
  • brown
  • gray
  • green
  • red
  • orange
  • purple
  • yellow

However, you can also build your own logger using the provided createLogger.

import { createLogger } from
Collapse
shubhambattoo profile image
Shubham Battoo

@itsmanojb something we were talking about the other day, what was that video you shared?

Collapse
itsmanojb profile image
Manoj Barman

That was from Angular firebase. Here the full video youtu.be/Mus_vwhTCq0

Collapse
sreubenstone profile image
Collapse
wangonya profile image
Collapse
alexr89 profile image
Alex

Is it possible to console.log within a width, so for example the entire width of the console?