Are you in the mood for a lightweight and fun project? We are going to build a custom-styled console logging class that you can use in place of console.log()
! We’re going to add some color and variation to our consoles. It will be similar in functionality to the debug npm package.
This should take no more than 10 minutes. To make things simpler, we can use CodeSandbox. It’s especially good for quick projects like this. We’ll be using the Vanilla template, which utilizes Parcel to give us features like bundling, importing, ES6 classes, etc. Check out this post for an introduction to Parcel if you’re curious to know more.
🏋️♂️ Recommended course ⤵
Wes Bos' ES6 for Everyone! I like to outline what my code should look like before I get started. Something like:
index.js
import CustomLogging from './CustomLogging'; const custom = new CustomLogging; const error = new CustomLogging('error'); error.setBodyStyle({ color: 'red', size: '2rem' }); // the output console.log('Regular log.'); custom.log('Hello there!'); error.log('Something bad happened!');
In the console tab (at the bottom of CodeSandbox), this outputs:
Our Strategy
We’re going to use an ES6 class to deliver this functionality. Because of Parcel, we can import/export this class to be used as a “package” of sorts. At it’s core this project will utilize the %c feature in the regular console.log()
method. See our article on the JavaScript console API for more details.
If you’re feeling adventurous, try to see what you can come up with on your own! Tweet your results to @alligatorio to show it off.
Let’s Get Coding
First, clear the initial code in index.js
so we’re starting fresh. Be sure to save as you go.
Create a new CustomLogging.js
file in the src
directory. Here’s a basic outline:
CustomLogging.js
class CustomLogging { log() { console.log("Hey, good lookin`!"); } } export default CustomLogging;
You’ll notice that this isn’t dynamic - we’re simply trying to make sure it works. To get this to be logged to the console, head over to the index.js
file where you’ll import the class, instantiate it, and then call the log()
method.
index.js
import CustomLogging from './CustomLogging'; const custom = new CustomLogging; custom.log();
Add Message and Styling
Now let’s pass in any message we want and begin some styling:
CustomLogging.js
class CustomLogging { log( body = "" // defaults to empty string ) { console.log( `%c${body}`, // everything after the %c is styled `color: green; font-weight: bold; font-size: 2rem;` ); } } export default CustomLogging;
…which is fired by:
index.js
// ... custom.log('May the Force be with you.');
Dynamic Styling
Let’s create a constructor to set defaults. We’ll then add a method to modify the styling on the fly:
CustomLogging.js
class CustomLogging { constructor() { // choose whatever defaults you'd like! this.body = { color: "#008f68", size: "1rem" }; } setBodyStyle({ color, size }) { // this will only set a value that is passed-in if (color !== undefined) this.body.color = color; if (size !== undefined) this.body.size = size; } log(body = "") { // adds dynamic styling via the template literals console.log( `%c${body}`, `color: ${this.body.color}; font-weight: bold; font-size: ${ this.body.size }; text-shadow: 0 0 5px rgba(0,0,0,0.2);` ); } } export default CustomLogging;
And again, we’ll use it:
index.js
// ... custom.setBodyStyle({ color: 'red' }); custom.log('Anger, fear, aggression; the dark side of the Force are they.');
What’s the Title?
Lastly, we’ll add a title into the constructor so that different instances can display their label:
CustomLogging.js
class CustomLogging { constructor(title) { this.title = { body: title || "---", color: "darkgrey", size: "1rem" }; this.body = { color: "#008f68", size: "1rem" }; } setTitleStyle({ color, size }) { if (color !== undefined) this.title.color = color; if (size !== undefined) this.title.size = size; } setBodyStyle({ color, size }) { if (color !== undefined) this.body.color = color; if (size !== undefined) this.body.size = size; } log(body = "") { // the second line is now the body because the first references the content after the first %c for the title console.log( `%c${this.title.body} | %c${body}`, `color: ${this.title.color}; font-weight: bold; font-size: ${ this.title.size };`, `color: ${this.body.color}; font-weight: bold; font-size: ${ this.body.size }; text-shadow: 0 0 5px rgba(0,0,0,0.2);` ); } } export default CustomLogging;
Invoke it with:
index.js
import CustomLogging from './CustomLogging'; const custom = new CustomLogging; const error = new CustomLogging('error'); error.setBodyStyle({ color: 'red', size: '2rem' }); console.log('Regular log..'); custom.log('Hello there!'); error.log('Something bad happened!');
🎉 Whoo! 🎉
We did it! Your console should now match the example at the top of the post. Pat yourself on the back, show a friend, or do whatever floats your boat.
Extra-Cool Functionality
What functionality can you add to this? Here are some ideas:
- More styling options
- Detect if body of
log()
method is an array or object and print them out in a styled way - Track time between each log and tag that onto the end
- Review the ‘debug’ npm package for more ideas.