Last active
June 22, 2021 18:23
-
-
Save pferreirafabricio/d2e27c01b6d4a278c2c59bc463ddb3db to your computer and use it in GitHub Desktop.
A simple logger script made with Winston package for NodeJS
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
const { createLogger, format, transports } = require('winston'); | |
const { combine, timestamp, label, printf } = format; | |
const config = require('./config'); | |
const isLogsEnabled = config.enableLogs; | |
/** | |
* Class to log in text files | |
*/ | |
class Logger { | |
/** | |
* Create the logger instance | |
*/ | |
static logger() { | |
return createLogger({ | |
level: 'info', | |
format: combine( | |
timestamp(), | |
printf(({ level, message, label, timestamp }) => { | |
return `${timestamp} [${level}]: ${message}`; | |
}), | |
), | |
defaultMeta: { service: 'user-service' }, | |
transports: [ | |
new transports.File({ filename: 'error.log', level: 'error' }), | |
new transports.File({ filename: 'info.log' }), | |
], | |
}); | |
} | |
/** | |
* Log an info message | |
*/ | |
static logInfo(message) { | |
if (isLogsEnabled) { | |
this.logger().info({ level: 'info', message: message }); | |
} | |
} | |
/** | |
* Log an error message | |
*/ | |
static logError(message) { | |
if (isLogsEnabled) { | |
this.logger().error({ level: 'error', message: message }); | |
} | |
} | |
} | |
module.exports = Logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment