Skip to content

Instantly share code, notes, and snippets.

@royz
Last active February 11, 2022 15:58
Show Gist options
  • Save royz/3a9812d869fd745837bf75fc47057da1 to your computer and use it in GitHub Desktop.
Save royz/3a9812d869fd745837bf75fc47057da1 to your computer and use it in GitHub Desktop.
A logger config using winston
const path = require('path')
const winston = require('winston')
const LOG_DIR = path.join(path.dirname(path.dirname(__filename)), 'logs')
const consoleLogFormat = winston.format.combine(
winston.format.timestamp({format: 'DD/MM/YYYY HH:mm:ss'}),
winston.format.colorize(),
winston.format.printf(({level, message, label, timestamp}) => {
return `${timestamp} ${label ? `[${label}] ` : ''}${level}: ${message}`;
}))
const fileLogFormat = winston.format.combine(
winston.format.timestamp({format: 'DD/MM/YYYY HH:mm:ss'}),
winston.format.printf(({level, message, label, timestamp}) => {
return `${timestamp} ${label ? `[${label}] ` : ''}${level}: ${message}`;
}))
const getLogger = (filePath) => {
const fileName = path.basename(filePath).split('.').at(0)
return winston.createLogger({
level: 'debug',
format: winston.format.simple(),
transports: [
new winston.transports.File({
filename: path.join(LOG_DIR, `${fileName}.log`),
format: fileLogFormat,
maxsize: 5 * 1024 * 1024, // 5 MB
maxFiles: 10
}),
new winston.transports.Console({format: consoleLogFormat})
],
})
}
module.exports = getLogger
/* --- Usage ---
* const logger = require('./logger')(__filename)
* logger.info('test')
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment