Last active
July 26, 2022 19:40
-
-
Save jtara1/3128cc6ed3dbea6d507b30967ab0e197 to your computer and use it in GitHub Desktop.
logger for JS - built up after several node projects
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 winston = require('winston'); | |
const { join, basename, dirname } = require('path'); | |
const fs = require('fs'); | |
const logform = require('logform'); | |
// const { MESSAGE } = require('triple-beam'); // prop for info in winston formater to expose the shown message | |
function filterMessagesFormat(filterFunc = () => true) { | |
const formatFunc = (info) => { | |
if (filterFunc(info.message)) return info; | |
return null; | |
}; | |
const format = logform.format(formatFunc); | |
format.transform = formatFunc; | |
return format; | |
} | |
module.exports = function createLoggerForWinston3(callingModule, logMessageFilterFunc = () => true) { | |
/** | |
* Returns the name of the parent dir and the basename (file name) | |
* e.g.: input: callModule.filename = '/home/user/james/file.js' | |
* returns: 'james/file.js' | |
* @returns {string} | |
*/ | |
function getDirnameAndBasename() { | |
if (!callingModule || !callingModule.filename) return 'no-module or filepath given'; | |
return join(basename(dirname(callingModule.filename)), basename(callingModule.filename)); | |
} | |
const myFormat = winston.format.combine( | |
winston.format.label({ label: getDirnameAndBasename() }), | |
winston.format.timestamp(), | |
winston.format.simple(), | |
filterMessagesFormat(logMessageFilterFunc), | |
); | |
const loggerFilePath = join(__dirname, 'logs/app.log'); | |
const options = { | |
level: process.env.LOGGING_LEVEL || 'info', | |
format: myFormat, | |
transports: [ | |
new winston.transports.Console({ | |
format: winston.format.combine( | |
winston.format.colorize(), | |
myFormat, | |
), | |
handleExceptions: false, | |
}), | |
new winston.transports.File({ | |
maxsize: 5e7, // 50 MB | |
maxFiles: 5, | |
filename: loggerFilePath, | |
handleExceptions: false, | |
}), | |
], | |
exitOnError: false, | |
}; | |
if (!fs.existsSync(dirname(loggerFilePath))) fs.mkdirSync(dirname(loggerFilePath)); | |
return winston.createLogger(options); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment