How to log events to a file in NodeJS?
I would like to log details regarding server requests into a file each time they occur.
What would be the optimal way to do this?
Currently using:
fs.open("./log_"+log_date.getMonth()+"-"+log_date.getDate(), "a+", function(err, fd){
if(err) {
sys.puts(err);
} else {
var logLineStr = JSON.stringify(log_line);
开发者_运维知识库 fs.write(fd, logLineStr,null,null,null, function(err, written, buffer) {
fs.close(fd);
});
}
});
Just use winston
http://nodejs.org/docs/v0.4.11/api/fs.html#fs.write
Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.
I'm going to assume this is handling requests and it would be possible to have multiple opens/writes happening at the same time.
You're better off writing a module that opens the file once when needed and maintains a Writable Stream to ensure you don't have any odd edge cases/race conditions.
精彩评论