Skip to content

Instantly share code, notes, and snippets.

@BinaryShrub

BinaryShrub/logger.ts

Last active Jun 27, 2020
Embed
What would you like to do?
Winston with console.log and colors support with util.format
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