Last active
August 21, 2023 20:43
-
-
Save BinaryShrub/790d97e34247d409f85b7c9434d0ddd5 to your computer and use it in GitHub Desktop.
Winston with console.log and colors support with util.format
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
import winston from 'winston'; | |
import util from 'util'; | |
const utilFormat = (enableColor: boolean) => { | |
const printFormat = winston.format.printf(({ level, message, timestamp }) => `${timestamp} ${level}: ${message}`); | |
const format = winston.format.combine(winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), { | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
transform: (info: any) => { | |
const args = info[Symbol.for('splat')] || []; | |
info.message = util.formatWithOptions({ colors: enableColor }, info.message, ...args); | |
info.level = info.level.toUpperCase()[0]; | |
return info; | |
}, | |
}); | |
return enableColor | |
? winston.format.combine(format, winston.format.colorize(), printFormat) | |
: winston.format.combine(format, printFormat); | |
}; | |
export const logger = winston.createLogger({ | |
level: 'debug', | |
transports: [ | |
new winston.transports.Console({ | |
format: utilFormat(true), | |
}), | |
new winston.transports.File({ | |
filename: 'program.log', | |
format: utilFormat(false), | |
}), | |
], | |
}); | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
console.log = (message: any, ...args: any) => logger.info('[CONSOLE.LOG]', message, ...args); | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
console.info = (message: any, ...args: any) => logger.info('[CONSOLE.INFO]', message, ...args); | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
console.warn = (message: any, ...args: any) => logger.warn('[CONSOLE.WARN]', message, ...args); | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
console.error = (message: any, ...args: any) => logger.error('[CONSOLE.ERROR]', message, ...args); | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
console.debug = (message: any, ...args: any) => logger.debug('[CONSOLE.DEBUG]', message, ...args); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment