Tuesday 2 July 2019

Applying styles to console messages


‘console’ object provide different methods to log trace, debug, warning and error messages.

For example,
HelloWorld.html
<!DOCTYPE html>

<html>
 <head>
  <title>Hello world</title>
  <meta charset="UTF-8">
 </head>
 
 <body>
  <script type="text/javascript">
   console.debug("Debug message");
   console.log("Log message");
   console.info("Information message");
   console.warn("Warning message");
   console.error("Error message");
  </script>
 </body>
</html>


Open ‘HelloWorld.html’ page in browser. In the console panel, you can see the log messages like below.


As you see the log messages, error and warning messages are appeared in different color.

How to style the log messages?
Log messages support inline css styles. You can specify inline styles using %c format specifier.

Example
var debugStyle = "color:green; font-weight-bold; font-size:50px"
console.debug("%c Debug message", debugStyle);

Above statements apply the style ‘debugStyle’ to the debug message.

HelloWorld.html
<!DOCTYPE html>

<html>
 <head>
  <title>Hello world</title>
  <meta charset="UTF-8">
 </head>
 
 <body>
  <script type="text/javascript">
   var debugStyle = "color:green; font-weight-bold; font-size:50px"
   var logStyle = "color:magenta; font-weight-bold; font-size:50px"
   var infoStyle = "color:darksalmon; font-weight-bold; font-size:50px"
   var warnStyle = "color:firebrick; font-weight-bold; font-size:50px"
   var errorStyle = "color:red; font-weight-bold; font-size:50px"
   
   console.debug("%c Debug message", debugStyle);
   console.log("%c Log message", logStyle);
   console.info("%c Information message", infoStyle);
   console.warn("%c Warning message", warnStyle);
   console.error("%c Error message", errorStyle);
  </script>
 </body>
</html>


Open above page in browser, you can see colorful messages in console.

Previous                                                 Next                                                 Home

No comments:

Post a Comment