Created
April 17, 2024 04:48
-
-
Save kumarldh/60b66ff3a117690123e44e60652a0fe5 to your computer and use it in GitHub Desktop.
My Winstorn logging set up
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 winston = require('winston'); | |
require('winston-daily-rotate-file'); | |
const { format } = winston; | |
const { combine, json, timestamp } = format; | |
const logDir = process.env.LOGDIR || './logs'; | |
const transports = []; | |
if (process.env.ENVIRONMENT === 'dev') { | |
transports.push( | |
new winston.transports.Console({ | |
format: winston.format.combine( | |
winston.format.colorize(), | |
winston.format.simple() | |
), | |
datePattern: 'YYYY-MM-DD', | |
}) | |
); | |
} else { | |
transports.push( | |
new winston.transports.DailyRotateFile({ | |
filename: `${logDir}/error-%DATE%.log`, | |
maxFiles: '30d', | |
level: 'error', | |
}) | |
); | |
transports.push( | |
new winston.transports.DailyRotateFile({ | |
filename: `${logDir}/combined-%DATE%.log`, | |
datePattern: 'YYYY-MM-DD', | |
maxFiles: '30d', | |
}) | |
); | |
} | |
/** | |
* Set a module name. | |
* | |
* @param {string} moduleName Use the module name here | |
* @returns | |
*/ | |
const getLogger = (moduleName) => { | |
if (!winston.loggers.has(moduleName)) { | |
winston.loggers.add(moduleName, { | |
level: 'info', | |
format: combine(timestamp(), json()), | |
transports, | |
defaultMeta: { module: moduleName }, | |
}); | |
} | |
return winston.loggers.get(moduleName); | |
}; | |
module.exports = getLogger; |
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 getLogger = require('./path/to/logger'); | |
const logger = getLogger('module-A'); | |
logger.info('Started logging!'); | |
try{ | |
// Refer to some undefined variable. Error! | |
const hello = `Hello ${world}!`; | |
}catch(o_O){ | |
logger.error('Something went wrong!'); | |
} |
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 path = require('path'); | |
const getLogger = require('./path/to/logger'); | |
// Use the file name as module name | |
const logger = getLogger(path.basename(__filename, path.extname(__filename))); | |
logger.info('Started logging!'); | |
try{ | |
// Refer to some undefined variable. Error! | |
const hello = `Hello ${world}!`; | |
}catch(o_O){ | |
logger.error('Something went wrong!'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment