3

I'm trying to log errors to a file in node.js. i tried winston:

winston= require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'error' }),
new (winston.transports.File)({ filename: 'error.log' })
]
});

I also tried console.error:

var log_file_err=
fs.createWriteStream(__dirname + '/error.log', {flags : 'a'});

var err_stdout = process.stderr;

console.error = function(d) { //
log_file_err.write(util.format(d) + '\n');
err_stdout.write(util.format(d) + '\n');
};

to generate an error i used:

function get_time(date)
{
     return date.getHours()+':'+date.getMinutes();
}
console.log(get_time(Date()));//instead of new Date()

i get no further errors(just the wanted undefined for Date()) but error.log stays empty."debug.log"(normal logging)where i use an overidden console.log works correctly.

2
  • no ideas? is this kind of error not written in the file because the app is crashing? if this the reason,how can i then log such errors to a file? Commented Feb 15, 2015 at 12:37
  • In your winston error log definition, if you pass in level: 'error' that will log fatal errors. I'm not sure how to capture all console.errors (still trying to figure that out) Commented Feb 25, 2015 at 17:40

1 Answer 1

5

Finally i found a solution which works perfectly for me:

var log_file_err=fs.createWriteStream(__dirname + '/error.log',{flags:'a'});  

process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
log_file_err.write(util.format('Caught exception: '+err) + '\n');
});
Sign up to request clarification or add additional context in comments.

1 Comment

This works okay for me. Doesn't give me the most details about what went wrong but at least it's something. Note that for this to work you need to define: const fs = require('fs'); and const util = require('util');

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.