I am using third-party modules which does console.log and there is no way to configure a custom logger for those modules. Is there any way I can reconfigure my app to pass all console.log and console.error to Winston logger?
Asked
Active
Viewed 252 times
2
-
try this https://stackoverflow.com/questions/55387738/how-to-make-winston-logging-library-work-like-console-log – Or Assayag Dec 05 '20 at 21:46
-
I used console.info = (message, params) => { this.logger.info(`Using Console:${message}`, params); }; console.warn = (message, params) => { this.logger.warn(`Using Console:${message}`, params); }; The problem console.log("hello","Bob"); prints hello {"0":"B","1":"o","2":"b"} – np4coding Dec 07 '20 at 21:59
1 Answers
1
I also recently wanted such a solution where my app is using winston for logging but there are some third party libs that use console logs directly. I wanted to redirect those messages through winston too. Here is a simplified snippet
const main_logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console({format: winston.format.cli()}),
new winston.transports.File({filename: `${LOG_DIR}/app.error.log`, level: 'error'}),
new winston.transports.File({filename: `${LOG_DIR}/app.log`})
]
})
const consoleLogger = function(level, message, ...params) {
main_logger.log(level, message)
if(params.length > 0) {
main_logger.log(level, JSON.stringify(params))
}
}
console.log = (...args) => {consoleLogger('info', ...args)}
console.info = (...args) => {consoleLogger('info', ...args)}
console.error = (...args) => {consoleLogger('error', ...args)}
console.warn = (...args) => {consoleLogger('warn', ...args)}
I do this in a logger.js
file that gets included into all other files that need a logger.

Nitish Puri
- 11
- 3