Created
October 27, 2020 06:43
-
-
Save mildronize/e38eea1217b967e42e7630ecadc6a049 to your computer and use it in GitHub Desktop.
Example for using Winston Logger ( Modify from https://github.com/danielfsousa/express-rest-boilerplate)
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'); | |
const { format } = winston; | |
const formatConsole = format.printf(( { message, level, timestamp }: any ) => { | |
return `${timestamp} ${level}: ${message}`; | |
}); | |
const formatFile = format.printf(( { message, level, timestamp }: any ) => { | |
return JSON.stringify({ message, level, timestamp }); | |
}); | |
var filename = module.filename.split('/').slice(-1); | |
const logger = winston.createLogger({ | |
level: 'info', | |
format: format.combine( | |
format.timestamp({ format: 'YYYY-MM-dd HH:mm:ss Z' }), | |
formatFile | |
), | |
transports: [ | |
// | |
// - Write to all logs with level `info` and below to `combined.log` | |
// - Write all logs error (and below) to `error.log`. | |
// | |
new winston.transports.File({ filename: 'error.log', level: 'error' }), | |
new winston.transports.File({ filename: 'combined.log' }), | |
], | |
}); | |
// | |
// If we're not in production then log to the `console` with the format: | |
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` | |
// | |
if (process.env.NODE_ENV !== 'production') { | |
logger.add(new winston.transports.Console({ | |
level: 'debug', | |
format: format.combine( | |
format.colorize(), | |
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), | |
format.label({ label: filename }), | |
formatConsole | |
), | |
})); | |
} | |
const testLogger = () => { | |
logger.error('error message'); | |
logger.warn('warn message'); | |
logger.info('info message'); | |
logger.verbose('verbose message'); | |
logger.debug('debug message'); | |
logger.silly('silly message'); | |
} | |
// testLogger(); | |
logger.stream = { | |
write: (message: any) => { | |
logger.info(message.trim()); | |
}, | |
}; | |
// https://medium.com/@muravitskiy.mail/cannot-redeclare-block-scoped-variable-varname-how-to-fix-b1c3d9cc8206 | |
export{}; | |
module.exports = logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment