3

On my CentOS 7.x server I am running Node (v6.7.0 and v0.10.36).

forever start /home/www/html/server/mynode.js

which runs following:

/usr/bin/node /home/www/html/server/mynode.js

CODE of mynode.js:

var http = require('http');
var net = require('net');
var url = require('url');
var io = require('socket.io').listen(3004);
io.set('log level', 1);

io.sockets.on('connection', function (socket) {
  socket.on('disconnect', function () {
    try{
      console.log(JSON.stringify(db));           
    } catch(dis) {
      console.log(dis);
    }

  });
});

How do i tell NodeJS or Linux to keep log? So that i can listen whats going on by tail -f /var/log/mynode.log ?

2
  • 1
    forever start /home/www/html/server/mynode.js > /var/log/mynode.log, for example Commented Sep 28, 2017 at 8:37
  • I tried that but it does not log the real console.log but it logs only the forever events. Commented Sep 28, 2017 at 8:39

2 Answers 2

12

You can overwrite your console.log

var fs = require('fs');

var trueLog = console.log;
console.log = function(msg) {
    fs.appendFile("/tmp/log.log", msg, function(err) {
        if(err) {
            return trueLog(err);
        }
    });
    //trueLog(msg); //uncomment if you want logs
}

Just put this snippet on top of your nodejs code.

Sign up to request clarification or add additional context in comments.

4 Comments

I have a heavy duty on the NodeJs script. If i use writeFile on heavy duty. My script will perform slow and it will make the service slow motion. Is there no other better way?
@YumYumYum well, you could use a buffer and write once it reached some limit, or even use triggered writes. If you need some help with that, just leave a PM ;)
Sure, can you please EDIT in the ANSWER with buffer method and another with triggered writes method? So that i can test and do bench mark on your 3 methods.
If var msg is something else other than string it will throw an error So you will need to add: msg = String(msg); For example if msg = 3 it will throw "msg.replace is not a function"
0

There's an option for capturing logs forever -o path/to/logfile start /home/www/html/server/mynode.js

From the docs -o OUTFILE Logs stdout from child script to OUTFILE

1 Comment

Same problem. -o only logs forever events not the nodejs myscript.js events. info: socket.io started warn: error raised: Error: listen EADDRINUSE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.