Custom Styled Javascript Console Logging

Posted By :Jayant Singh Parmar |31st December 2018

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. This should take no more than ten 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.

I like to outline what my code should look like before I get started. Something like:

        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:

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.

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:

        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.

        import CustomLogging from './CustomLogging';        const custom = new CustomLogging;                    custom.log();            

Now let’s pass in any message we want and begin some styling:

        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: 

        custom.log('May the Force be with you.');            

Let’s create a constructor to set defaults. We’ll then add a method to modify the styling on the fly:

        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:

        custom.setBodyStyle({ color: 'red' });        custom.log('Anger, fear, aggression; the dark side of the Force are they.');          

Lastly, we’ll add a title into the constructor so that different instances can display their label:

        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:

        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!');      

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.

 


About Author

Jayant Singh Parmar

Jayant has more than 5+ years of industry experience as a frontend developer. He has good knowledge of technologies like Angular, reactJS, HTML, CSS, javascript etc. He is proficient in building complex UI designs, implentation of complex logics on frontend, API integrations, development and deployments and have been part of successfully delivering services on various client projects like Virgin Media, Hp1t and Jabburr He is a quick learner and keen to learn new technologies.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us