Reputation: 3353
I was wondering if node.js (or express framework) has any kind of built in access logging like grails has for example?
I have grails application that runs on tomcat and it automatically generates /apache-tomcat-7.0.42/logs/localhost_access_log.2013.10.30.txt
file in which are logs about request response like this one:
[30/Oct/2013:00:00:01 +0000] [my-ip-address] [http-bio-8080-exec-18] "GET /my-service/check HTTP/1.0" [200] [took: 1 milis]
This logs are written automatically by system and I don't have to worry about that.
So what about node.js?
Thanks for any help!
Ivan
Upvotes: 21
Views: 45571
Reputation: 4635
It's not built in but really easy to configure. You can use express-winston and add to the express middleware stack. morgan
does not let you log the request body but expressWinston does:
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
Example in coffeescript:
expressWinston.requestWhitelist.push('body')
expressWinston.responseWhitelist.push('body')
app.use(expressWinston.logger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
})
],
meta: true, // optional: control whether you want to log the meta data about the request (default to true)
msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
expressFormat: true, // Use the default Express/morgan request formatting, with the same colors. Enabling this will override any msg and colorStatus if true. Will only output colors on transports with colorize set to true
colorStatus: true, // Color the status code, using the Express/morgan color palette (default green, 3XX cyan, 4XX yellow, 5XX red). Will not be recognized if expressFormat is true
ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
}));
Upvotes: 2
Reputation:
As of now, most middleware (like logger) is no longer bundled with express and must be installed separately.
Short answer:
First, install morgan
:
npm install morgan
Then use it for logging:
app = express();
var morgan = require('morgan')
...
app.use(morgan('combined'))
Documentation is here.
Upvotes: 14
Reputation: 14399
edit As of express 4.0.0
this solution is apparently no longer enough. Check out the answer from whirlwin for an updated solution.
You can use app.use(express.logger());
Documented here: http://www.senchalabs.org/connect/logger.html
Upvotes: 10
Reputation: 16541
In newer versions of Express (4.0.0 at the time of writing), the logger is no longer part of Express, so you have to include it as a dependency manually. It is now called morgan.
So, in package.json
, add morgan as a dependency:
"dependencies": {
...
"morgan": "*"
...
}
And in your Express configuration, add:
app.use(require('morgan')('dev'));
Now logging should work more or less like before. :-)
Upvotes: 27