Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept console logs to file Nodejs

I am working on a game using NodeJs, and realized it would be immensly helpful to have access to old console.log output. The mechanics and calculations get rather complicated, and it would be nice to have access to them later to search through and do some data analysis on them to find the correct values for my modifiers (battle mechanics). At the same time, I want to see console.log in the console as well.


I know this isn't possible with regular javascript, (see This), but I was hoping npm had a package of some way to intercept logs and log them to a file on the server. Any thoughts?

like image 213
Ethan Avatar asked Sep 05 '25 21:09

Ethan


1 Answers

You can intercept console.log like so

var cl = console.log

console.log = function(...args){
  // your custom logging logic here
  cl.apply(console, args)
}
like image 157
jshawl Avatar answered Sep 08 '25 11:09

jshawl