in order to extend console.log
in the browser with a few extras (like a timestamp and loglevel) I came up with the following implementation:
const LOG_LEVELS = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
NONE: 4,
};
const Logger = {
debug:
loglevel === LOG_LEVELS.DEBUG
? Function.prototype.bind.call(
console.log,
console,
new Date().toISOString() + ": [DEBUG]"
)
: function () {},
info:
loglevel <= LOG_LEVELS.INFO
? Function.prototype.bind.call(
console.log,
console,
new Date().toISOString() + ": [INFO]"
)
: function () {},
warn:
loglevel <= LOG_LEVELS.WARN
? Function.prototype.bind.call(
console.log,
console,
new Date().toISOString() + ": [WARN]"
)
: function () {},
error:
loglevel <= LOG_LEVELS.ERROR
? Function.prototype.bind.call(
console.error,
console,
new Date().toISOString() + ": [ERROR]"
)
: function () {},
};
It has the advantage of sustaining the file and line-of-code information the same way as console.xxx
calls are already doing that.
But: Obviously the date information is being generated together with the bind
and not when calling Logger.debug
etc., so all the log entries are showing the same date/time information.
Is there a way (maybe using apply?) to generate the date information at the time the Logger.xxxx
functions execute? I tried a few things but none of them came even close. That's why I post the original code.