Created
November 17, 2014 14:02
-
-
Save octavian-nita/f491c532b697e087c93f to your computer and use it in GitHub Desktop.
Simple logging for Node.js
This file contains hidden or 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
| 'use strict'; | |
| var config = require('./config'); | |
| /** | |
| * @param {string} [level=INFO] by default, 'expected' (from a formatting point of view) values are: ERROR, WARN, | |
| * WARNING, INFO and DEBUG. | |
| */ | |
| function log(level, messageOrError /* messagePart1, messagePart2, ... */) { | |
| var | |
| time = new Date().toISOString().replace(/[TZ]/gi, ' ').trim(), | |
| args = Array.prototype.slice.call(arguments, 2), | |
| logfn = console.log; | |
| level = (level && level.trim().toUpperCase()) || 'INFO'; | |
| if (level === 'DEBUG' && !config.debug.on) { | |
| return; | |
| } | |
| if (level === 'ERROR') { | |
| logfn = console.error; | |
| } else if (level === 'WARN' || level === 'WARNING') { | |
| logfn = console.warn; | |
| level = 'WARN '; // use the 'short' level text | |
| } else if (level === 'INFO') { | |
| level = 'INFO '; | |
| } | |
| if (messageOrError && messageOrError instanceof Error) { | |
| if (args && args.length) { | |
| logfn.apply(console, [time, level, '-'].concat(args)); | |
| } | |
| logfn.call(console, time, level, '-', messageOrError.stack ? messageOrError.stack : messageOrError); | |
| } else { | |
| logfn.apply(console, [time, level, '-', messageOrError].concat(args)); | |
| } | |
| } | |
| exports.log = log; | |
| exports.debug = function() { | |
| log.apply(null, ['DEBUG'].concat(Array.prototype.slice.call(arguments, 0))); | |
| }; | |
| exports.error = function() { | |
| log.apply(null, ['ERROR'].concat(Array.prototype.slice.call(arguments, 0))); | |
| }; | |
| exports.warn = function() { | |
| log.apply(null, ['WARN'].concat(Array.prototype.slice.call(arguments, 0))); | |
| }; | |
| exports.info = function() { | |
| log.apply(null, ['INFO'].concat(Array.prototype.slice.call(arguments, 0))); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment