Reputation: 1748
I'm a newbie to development and earlier this year started playing around with node.js and liked it very much. I've been gradually increasing my logging mechanism in node.js. Starting from console.log and now currently using a RAM disk to log everything to a file in RAM disk.
This method of logging into RAM disk is close to what I desire. I don't want a permanent file, but I do want some persistence so that if my node.js crashes I don't loose my prior logs. I am using forever to restart node automatically, that means I do not have an active terminal where I can watch the logs and errors in real time. Instead I have a GET method that reads all the logs from the RAM Disk and serves it back to me.
Here is my code for saving logs in file in RAM disk and in memory buffer:
function generateLog(level, logMsg) {
var logLevel;
if(level == levelOff)
return; // no need to go any further, logging has been disabled.
else if(level == levelDebug)
logLevel = "DEBUG: ";
else if(level == levelInfo)
logLevel = "INFO: ";
else if(level == levelWarning)
logLevel = "WARNING: ";
else if(level == levelError)
logLevel = "ERROR: ";
else if(level == levelException)
logLevel = "EXCEPTION: ";
if (level >= loggingLevel){
console.log(logLevel + logMsg);
checkIfFileExists(logFile, function(err,status){
if(err){ // if file does not exist, save it to memory buffer
logBuffer = logBuffer + '<br>' + logLevel + logMsg; // memory
}
else{ // file exists - save it to this file in RAM_disk
fs.appendFile(logFile, logLevel + logMsg + '\n', function(err) {
if(err) {
return console.log(err);
}
});
}
});
}
}
The problem is that when the node process crashes due to an exception or error then that does not get logged to the RAM disk.
Please advice how to log errors and exceptions in node.
Upvotes: 1
Views: 5432
Reputation: 833
When nodejs detects error that is not handled, it will just crash. You need to have a process.on('uncaughtException') hook, to catch and log the error. An example would be;
process.on('uncaughtException', function (err) {
if (err) {
console.log("caughtException but no error msg" + err.stack);
process.exit(1);
}
});
This hook should only be used to detect the problem. When this happens typically there is no way to recover, so it is good idea to exit the process. You will have the stack in the log to look at actual failure.
You may also want to add process.on('exit') hook, to determine if the process is crashed by application error or by other means; such as "systemctl restart".
Upvotes: 4