How to use Morgan logger?

Green picture Green · May 6, 2014 · Viewed 146.6k times · Source

I cannot log with Morgan. It doesn't log info to console. The documentation doesn't tell how to use it.

I want to see what a variable is. This is a code from response.js file of expressjs framework:

var logger = require("morgan");

res.render = function(view, options, fn){
  options = options || {};
  var self = this;
  var req = this.req;
  var app = req.app;

  // support callback function as second arg
  if ('function' == typeof options) {
    fn = options, options = {};
  }

  // merge res.locals
  options._locals = self.locals;

  // default callback to respond
  fn = fn || function(err, str){
    if (err) return req.next(err);
    self.send(str);
  };

  // Here I want to see what fn is
  // But it doesn't show me anything in console
  // How to use it?
  logger(fn);

  // render
  app.render(view, options, fn);
};

How to use Morgan?

Answer

NikhilWanpal picture NikhilWanpal · May 12, 2014

Seems you too are confused with the same thing as I was, the reason I stumbled upon this question. I think we associate logging with manual logging as we would do in Java with log4j (if you know java) where we instantiate a Logger and say log 'this'.

Then I dug in morgan code, turns out it is not that type of a logger, it is for automated logging of requests, responses and related data. When added as a middleware to an express/connect app, by default it should log statements to stdout showing details of: remote ip, request method, http version, response status, user agent etc. It allows you to modify the log using tokens or add color to them by defining 'dev' or even logging out to an output stream, like a file.

For the purpose we thought we can use it, as in this case, we still have to use:

console.log(..);

Or if you want to make the output pretty for objects:

var util = require("util");
console.log(util.inspect(..));