Created
August 15, 2018 21:12
-
-
Save mexisme/0ae6a8896af671ef7115218fae8aab8f to your computer and use it in GitHub Desktop.
Simple log-library, Node-4 friendly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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