在node.js(快速框架)中build立访问日志

我想知道是否node.js (或expression框架)有任何内置的访问日志logging像grails例如?

我有grails应用程序运行在tomcat上,它会自动生成/apache-tomcat-7.0.42/logs/localhost_access_log.2013.10.30.txt文件,其中有关于请求响应的日志如下所示:

 [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] 

这个日志是由系统自动编写的,我不必担心这个。

那么node.js呢?

谢谢你的帮助!

伊万

编辑从expression4.0.0这个解决scheme显然已经不够了。 查看来自whirlwin的更新解决scheme的答案。

你可以使用app.use(express.logger());

logging在这里: http : //www.senchalabs.org/connect/logger.html

在较新版本的Express(编写本文时为4.0.0 )中,logging器不再是Express的一部分,因此您必须手动将其作为依赖项包含在内。 现在叫做摩根 。

所以,在package.json ,添加摩根作为依赖:

 "dependencies": { ... "morgan": "*" ... } 

在您的快速configuration中,添加:

 app.use(require('morgan')('dev')); 

现在日志应该像以前一样工作。 🙂

截至目前,大多数中间件(如logging器)不再与express捆绑在一起,必须单独安装。

简单的回答:首先,安装morgan

 npm install morgan 

然后用它来logging:

 app = express(); var morgan = require('morgan') ... app.use(morgan('combined')) 

文档在这里

这不是内置的,但很容易configuration。 您可以使用express-winston并将其添加到快速中间件堆栈中。 morgan 不让你login请求体,但expression温斯顿:

 expressWinston.requestWhitelist.push('body'); expressWinston.responseWhitelist.push('body'); 

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. Eg "{{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 })); 
Interesting Posts