Last active
February 11, 2022 15:58
-
-
Save royz/3a9812d869fd745837bf75fc47057da1 to your computer and use it in GitHub Desktop.
A logger config using 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
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