Reusable Log Object

#codesnippet #javascript

Abstracts log levels so more complex loggers (like networked or structured) can be swapped in / out without major refactoring, like is the case with direct use of console.log().

const log = {
  any(level, msg, data) {
    console.log(
      `${new Date().toISOString()} ${level.toUpperCase()} ${msg}`,
      ...data
    )
  },
  warn(msg, ...data) {
    this.any('warn', msg, data)
  },
  debug(msg, ...data) {
    this.any('debug', msg, data)
  },
  info(msg, ...data) {
    this.any('info', msg, data)
  },
  trace(msg, ...data) {
    this.any('trace', msg, data)
  },
}