Created
December 4, 2018 11:17
-
-
Save hamzaPixl/a2b1041ff790a27726c8e3b74808e241 to your computer and use it in GitHub Desktop.
Logger js. Using moment and winston
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
| /** | |
| * Usage: | |
| * const logger = require('./logger').init('name'); | |
| * | |
| * > logger.info('message logged'); | |
| * | |
| */ | |
| const moment = require('moment'); | |
| const winston = require('winston'); | |
| let logger = null; | |
| const tsFormat = () => moment.utc().format('YYYY-MM-DD - HH:mm:ss.SSS'); | |
| /** | |
| * Initialize the loggers | |
| * | |
| * @param {String} logFileName - The log file name for file logger | |
| */ | |
| const init = function init(loggerName, level = 'info') { | |
| const transports = [ | |
| new (winston.transports.Console)({ | |
| level, | |
| handleExceptions: true, | |
| humanReadableUnhandledException: true, | |
| prettyPrint: false, | |
| timestamp: tsFormat, | |
| json: false, | |
| colorize: true, | |
| }), | |
| ]; | |
| if (loggerName) { | |
| transports.push(new (winston.transports.File)({ | |
| level: 'warn', | |
| handleExceptions: true, | |
| humanReadableUnhandledException: true, | |
| filename: `${loggerName}.log`, | |
| timestamp: tsFormat, | |
| })); | |
| } | |
| logger = new winston.Logger({ | |
| transports, | |
| }); | |
| logger.stream = { | |
| write: function write(message) { | |
| logger.info(message); | |
| }, | |
| }; | |
| return logger; | |
| }; | |
| const warn = function warn(message, err) { | |
| logger.warn(message, err); | |
| }; | |
| const error = function error(message, err) { | |
| logger.error(message, err); | |
| }; | |
| const fatal = function fatal(message, err) { | |
| logger.fatal(message, err); | |
| }; | |
| const info = function info(message) { | |
| logger.info(message); | |
| }; | |
| const debug = function debug(message) { | |
| logger.debug(message); | |
| }; | |
| module.exports = { | |
| init, | |
| warn, | |
| error, | |
| info, | |
| fatal, | |
| debug, | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment