How to log stack traces in node.js

21,631

Solution 1

You can get this text off of the .stack property from any Error. For instance:

try {
    throw new Error();
} catch (e) {
    console.log(e.stack);
}

or just new up an error for the purposes of getting the stack trace

console.log(new Error().stack)

Solution 2

If you use winston, you can add this:

winston = require('winston');

logger = expandErrors(new winston.Logger());

logger.info(new Error("my error"));

// Extend a winston by making it expand errors when passed in as the 
// second argument (the first argument is the log level).
function expandErrors(logger) {
  var oldLogFunc = logger.log;
  logger.log = function() {
    var args = Array.prototype.slice.call(arguments, 0);
    if (args.length >= 2 && args[1] instanceof Error) {
      args[1] = args[1].stack;
    }
    return oldLogFunc.apply(this, args);
  };
  return logger;
}

and then you get winston loggers with stack traces. Also is in a gist.

Solution 3

there's a function for that: console.trace()

In case you don't want to log to console you can get the stack trace string value using new Error().stack

Share:
21,631
Chris Abrams
Author by

Chris Abrams

Updated on July 09, 2022

Comments