How do I create formatted javascript console log messages
To embellish your console logs, employ console.log()
paired with %c
and, our stylist star, CSS. In a nutshell:
This outputs "Formatted message" in bold red, showcasing direct style application. Tweak the CSS string for a spectrum of effects.
Diving deeply: Nullius in Verba
Going beyond the simple text styles, you can chain multiple style rules using %c
, multiple times. This allows you to apply distinct styles to different parts of your message:
Get your hands dirty in the dev console, testing the styles to experience them live. This interactive education can assist in vivifying your logs' visual presentation.
Unlock the potential: CSS is your playground
You can apply complex formations by using several %c
segments:
Through playing with a variety of CSS properties like background
, padding
, or border
, you can unearth new avenues. For consistent styling, consider creating a customLog function using preset styles.
Debugging deluxe: Treat yourself!
When debugging or rendering structured data, why don't style object representations like this:
Always match style arguments with %c
placeholders to avoid breaking the party.
Be safe: Stick to the rules
Avoid any exploit or non-standard methods. Directly apply documented features to ensure cross-browser compatibility and safe log messages.
Style references
Here are the visual examples of style references for a quick glance:
Costume (Style) | Visual Effect |
---|---|
'font-weight: bold' | Bold Words |
'color: red' | Red Text |
'background-color: blue; color: white' | 🔵 Blue Background with White Text |
Pro tips: Get the edge
Intelligent style adaptation
Extract the styles from DOM elements and apply them to your logs:
This applies the computed CSS of an element and creates a unified look between your application and the debug messages in the console.
Custom log functions: Consistency made easy
Build a customLog()
function for recurrently used styles:
Easily customize and reapply styles across your code with this function.
Object linking: Clarity beyond text
For comprehensive output, venture into object linking:
Inspect linked objects right in the console log!
Was this article helpful?