事实证明,您可以覆盖 app.js 文件顶部的控制台功能,并使其在所有其他模块中生效。我得到的结果好坏参半,因为我的一个模块被分叉为child_process。一旦我将该行也复制到该文件的顶部,一切正常。
为了记录,我安装了模块console-stamp(npm install console-stamp --save),并将这一行添加到app.js和childProcess.js的顶部:
// add timestamps in front of log messages
require('console-stamp')(console, '[HH:MM:ss.l]');
我现在的问题是连接记录器的:date 格式使用UTC 格式,而不是我在其他控制台调用中使用的格式。这很容易通过注册我自己的时间格式来解决(并且作为副作用,需要console stamp 附带的dateformat 模块,而不是安装另一个):
// since logger only returns a UTC version of date, I'm defining my own date format - using an internal module from console-stamp
express.logger.format('mydate', function() {
var df = require('console-stamp/node_modules/dateformat');
return df(new Date(), 'HH:MM:ss.l');
});
app.use(express.logger('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));
现在我的日志文件看起来井井有条(更好的是,可解析):
[15:09:47.746] staging server listening on port 3000
[15:09:49.322] connected to database server xxxxx successfully
[15:09:52.743] GET /product 200 - - 127.0.0.1 - 214 ms
[15:09:52.929] GET /stylesheets/bootstrap-cerulean.min.css 304 - - 127.0.0.1 - 8 ms
[15:09:52.935] GET /javascripts/vendor/require.js 304 - - 127.0.0.1 - 3 ms
[15:09:53.085] GET /javascripts/product.js 304 - - 127.0.0.1 - 2 ms
...