When developing websites and applications with JavaScript we often write console.log() messages between our lines of code.
Things can get a little bit annoying when your console starts to fill up with a lot of these messages and you might feel like you want to focus just on a certain part of the program.
I have wished many times that there would be an easy way to temporarily turn off messages that I don’t need, but commenting them out one by one feels a little bit too tedious. That’s why I decided to develop a custom console log function that will only log I messages that have the highest priority number that way I can basically shut off all other messages by giving one of my messages up higher priority value. This lets me really focus on the message that I need to focus on . So here is a custom myLog() function that I’m now calling instead of console log and it takes two arguments:
the thing to log
and a priority number
If I set the priority number of one of my calls to be high higher than the others then only that message will be shown. So for example if other priorities are number one but I do a new console log that has a priority of two, then only that log message with the highest priority will be shown .
let priority = 0;
let lastLog;
function myLog(message, logPriority) {
if (logPriority >= priority) {
lastLog = message;
priority = logPriority;
}
console.log(lastLog);
}
//use like this
myLog(`my log message and variable ${myvar}`, 1)
One downside with this method is that unlike regular console logs it doesn’t automatically show you the file and line of code that produced the console log. We can remedy this by writing a little helper function that will use the error logging capabilities in order to also include the file and the line information together with the console log. The fileInfo is now an optional third argument that you can use:
let priority = 0;
let lastLog;
function myLog(message, logPriority, fileInfo) {
if (logPriority >= priority) {
lastLog = message;
priority = logPriority;
}
console.log(lastLog);
if (fileInfo){ //check that it's not undefined
console.log(`Current file: ${fileInfo.filename}, line number: ${fileInfo.lineNumber}`);
}
}
//for getting line number and file name
function getFileInfo() {
const err = new Error();
const stackTrace = err.stack.split('\n')[2].trim();
const matchResult = /\((.*):(\d+):\d+\)/.exec(stackTrace);
const absoluteFilename = matchResult[1];
const lineNumber = matchResult[2];
const currentDir = window.location.href.split('/').slice(0, -1).join('/');
const relativeFilename = absoluteFilename.replace(currentDir, '');
return {
filename: relativeFilename,
lineNumber: lineNumber
};
}
//use like this:
myLog(`dialogueIDSent: ${dialogueIDSent}`, 1, fileInfo = getFileInfo());