Prefixing the console.log while keeping its ability to inform you about the code line wherefrom it was called is little hacky but useful to use in your own javascript applications. I was scratching my head while I was coding in one of my projects, I was up to a point that I needed a more customizable, application specific, logger functionality. The first thing I wanted was to prefix the console.log function with my own text (line:2) and some UTF-8 icons, so when I’m debugging the app I’d be aware of what is coming from my application logger and what isn’t. The mistake I made was to put console.log inside my closure or named function and call the closure/function with the log message as an argument, instead of creating and calling the bound log function.
After researching I found out that window.console or console should be bound and add my prefix variable as an argument.
Here is the full documentation of .bind if you’d like to read more about it. If not here’s a quick snippet
1 |
function.bind( thisArg [, arg1[, arg2[, ...]]] ) |
A working example can be found at codepen