On styled console labels
January 22, 2023
Did you know you can style your browser console.log()
output? If you’ve ever found it difficult to quickly scan or parse your application’s logs, adding unique styles for specific types of logs can help.
Consider this:
[ok] Operation successful.[error] Operation failed!
The output is fine, and the text-only labels make it pretty easy to quickly scan the output. It could be better though. What about this?
okOperation successful.errorOperation failed!
Awesome! Now we can quickly scan the logs by color too. Maybe we want to tag logs by functionality:
apiGET https://example.com/api/foo 200trackpageview: /blog
Implementation
This is accomplished by using format specifiers in your arguments for console.log()
. Here is the example from earlier with its inputs:
> console.log("%cok", "color:white;background:green;border-radius:4px;padding:2px 4px;margin-right:1ch;", "Operation successful.")okOperation successful.> console.log("%cerror", "color:white;background:red;border-radius:4px;padding:2px 4px;margin-right:1ch;", "Operation failed!")errorOperation failed!
Any text after the %c
format specifier will have the CSS from the next argument applied.
Demo
Let's try it out! Try filling in the arguments to console.log()
below.
> console.log("%cok", "color:white;background:green;border-radius:4px;padding:2px 4px;margin-right:1ch;", "Operation successful.")okOperation successful.> console.log("%cerror", "color:white;background:red;border-radius:4px;padding:2px 4px;margin-right:1ch;", "Operation failed!")errorOperation failed!> console.log()
Make it a helper method
It's not really practical to write out the styles like this every time. Let's create a little helper method called logWithLabel
.
Here's the output of the logWithLabel
call:
trackpageview: /blog
You could take this even further, and build a logger instance with pre-defined labels for specific actions, or even unique labels for different log levels. I also like to pair labeled logs with console.group()
for rich, structured logs.