Skip to content

Instantly share code, notes, and snippets.

@pferreirafabricio
Last active June 22, 2021 18:23
Show Gist options
  • Save pferreirafabricio/d2e27c01b6d4a278c2c59bc463ddb3db to your computer and use it in GitHub Desktop.
Save pferreirafabricio/d2e27c01b6d4a278c2c59bc463ddb3db to your computer and use it in GitHub Desktop.
A simple logger script made with Winston package for NodeJS
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