Im not a node developer by nature and I have this project and I am trying to debug something. And I notice that the logger is logging to process.stdout .... How can I tail -f this in a running node server?
Asked
Active
Viewed 524 times
0
-
`node server | tee your-log.txt&; tail -f your-log.txt` – ronnie bermejo Jun 28 '19 at 02:42
-
? ... i dont understand that – slipperypete Jun 28 '19 at 02:43
-
If you control how to start node, you can redirect the output `process.stdout` into a file via the command line, then do the `tail -f` on it – ronnie bermejo Jun 28 '19 at 02:48
-
Thats not an option... there is no way to see it without doing that? – slipperypete Jun 28 '19 at 02:49
-
Check: https://stackoverflow.com/questions/1323956/how-to-redirect-output-of-an-already-running-process/1323999#1323999 – ronnie bermejo Jun 28 '19 at 02:53
-
if your are in a *ix system, this probably the best: `strace -ewrite -p $PID` – ronnie bermejo Jun 28 '19 at 02:55
1 Answers
0
Option #1 - Most common
Just run your script/server like this:
node ./my-server.js >/path/to/logs/my-server.log 2>&1
Then to tail ...
tail -f /path/to/logs/my-server.log
NB.: For production, you might want to use something like logrotate in addition.
Option #2 - For hackers
Wherever you are using process.stdout.write(msg)
or console.log(msg)
, you can use process.emit('logger#receiver-id', JSON.stringify({content: msg}))
// sample.js
function doSomething() {
// console.log('Hello world');
var msg = 'Hello World !';
process.emit('logger#catch-all', JSON.stringify({content: msg}))
}
doSomething();
// tail.js
function onPayload(payload) {
var msg = JSON.parse(payload).content;
process.stdout.write(msg);
}
function registerEvent() {
process.on('logger#catch-all', onPayload);
}
registerEvent();
Then you can now get your logs by running (first) tail.js
, then sample.js
This method is just a sample of what you can do by considering logs as events ... You can then write your own containers and format payloads depending on where your logs are going: stdout, file, monitoring tools ...
You might have to override console.<method>()
if you do not want to use directly process.emit(...)
.