Skip to content

Instantly share code, notes, and snippets.

@mexisme
Created August 15, 2018 21:12
Show Gist options
  • Save mexisme/0ae6a8896af671ef7115218fae8aab8f to your computer and use it in GitHub Desktop.
Save mexisme/0ae6a8896af671ef7115218fae8aab8f to your computer and use it in GitHub Desktop.
Simple log-library, Node-4 friendly
/*
Logging module
*/
'use strict'
const Logger = function(options) {
this.init(options)
}
const p = Logger.prototype
const defaultLevel = 'info'
const levels = ['debug', 'info', 'warn', 'error']
p.init = function(options) {
this.logLevel = (options && options.logLevel) || defaultLevel
}
p.shouldLog = function(level) {
return (levels.indexOf(level) >= levels.indexOf(this.logLevel))
}
p.stringify = function(messages) {
const stringified = []
// eslint-disable-next-line no-plusplus
for (let i = 0; i < messages.length; i++) {
let message = messages[i]
if (typeof message !== 'string') {
message = JSON.stringify(message)
}
stringified.push(message)
}
return stringified
}
p.log = function(level) {
if (!this.shouldLog(level)) return
const messages = this.stringify([].slice.call(arguments).slice(1))
// eslint-disable-next-line no-plusplus
for (let i = 0; i < messages.length; i++) {
const count = (messages.length > 1) ? `:${i}` : ''
// eslint-disable-next-line no-console
console.log(`${level}${count}: ${messages[i]}`)
}
}
p.debug = function() {
// eslint-disable-next-line prefer-rest-params
const args = ['debug'].concat([].slice.call(arguments))
// eslint-disable-next-line prefer-spread
this.log.apply(this, args)
}
p.info = function() {
// eslint-disable-next-line prefer-rest-params
const args = ['info'].concat([].slice.call(arguments))
// eslint-disable-next-line prefer-spread
this.log.apply(this, args)
}
p.warn = function() {
// eslint-disable-next-line prefer-rest-params
const args = ['warn'].concat([].slice.call(arguments))
// eslint-disable-next-line prefer-spread
this.log.apply(this, args)
}
p.error = function() {
// eslint-disable-next-line prefer-rest-params
const args = ['error'].concat([].slice.call(arguments))
// eslint-disable-next-line prefer-spread
this.log.apply(this, args)
}
module.exports = Logger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment