Adding Style to console.log Messages

Nil Seri
3 min readFeb 12, 2024

Create Custom Formatted console.log Messages in Your Project

Photo by Elena Mozhvilo on Unsplash

You may have noticed, some libraries or browser add-ons have their own console logging styles.

I have been using Requestly’s Chrome add-on for mocking response data and I noticed that they label their logs such as:

Lately, I have implemented service-worker with workbox and during development you can enable workbox logging and trace actions:

https://developer.chrome.com/docs/workbox/troubleshooting-and-logging

As you can see, these projects have their unique style for logging.

You can also implement this in your own project. For this, I added new methods to my project’s UtilService (util.service.ts file):

import * as moment from 'moment';

public static logInfo(info: string[]): void {
console.log(
'%cMy Project',
'color:#0469d0;border:1px solid #0469d0;padding:1px 2px;border-radius: 2px',
`[${moment(Date.now()).format('DD/MM/YYYY hh:mm:ss')}]`,
...info);
}

public static logError(error: string[]): void {
console.error(
'%cMy Project',
'color:#f05f6d;border:1px solid #f05f6d;padding:1px 2px;border-radius: 2px',
`[${moment(Date.now()).format('DD/MM/YYYY hh:mm:ss')}]`,
...error);
}

For date formatting, I used “moment” library. You can choose whichever format you like as described in their homepage.

Do not forget to add “%c” to the beginning of where you want to apply custom css. The following parameter now must be the css code.

You can also enable timestamp for logs via this setting in your Chrome Developer Tools. Just click on settings icon on the right hand side:

Scroll down little by little until you come across “Console” settings and enable “Show timestamps”.

Now, timestamp info is added to the beginning of the logs:

Added dummy code in my component’s ngOnInit method for testing:

this.isNewVersionAvailable = false;
UtilService.logInfo(this.isNewVersionAvailable ? ['A new version is available.'] : ['Already on the latest version.']);
try {
throw new Error('Parameter is not a number!');
} catch (error) {
UtilService.logError(['Failed to check for updates:', error]);
}

The output:

You can also give multiple css formats to your console log. As you can see I have now multiple “%c”s in my first input (message to log) and each custom css code appears as separate inputs following the message input:

console.log(
'%cMy Project %cStarts Now',
'color: pink;', 'color: purple;'
);

Add emojis (you can open your emoji keyboard on Mac with Command + Control + Space combination):

console.log(
'%cMy Project shines bright like a 💎',
'color: red;'
);

Voilà!

--

--

Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏻‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨