将时间戳添加到所有控制台消息

我有一个完整的, 部署的基于Express的项目,其中有许多console.log()和console.error()语句。 该项目永远运行,将stdout和stderr指向2个独立的文件。

这一切工作得很好,但现在我错过了时间戳 – 要确切地知道何时发生错误。

我可以在整个代码中进行一些search/replace,或者在每个文件中使用一些覆盖控制台的npm模块,但我不想触及每个模型/path文件,除非我绝对必须。

有没有办法,也许Express中间件,这将允许我添加一个时间戳到每个调用,或者我必须手动添加它?

事实certificate,您可以覆盖app.js文件顶部的控制台function,并使其在每个其他模块中生效。 我得到的结果混杂,因为我的一个模块分叉为一个child_process 。 一旦我将该行复制到该文件的顶部,所有的作品。

为了logging,我安装了模块控制台标记( 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连接logging器的:date格式使用UTC格式,而不是我在其他控制台调用中使用的格式。 这很容易通过注册我自己的时间格式来解决(并且作为副作用,需要使用console stampdateformat模块,而不是安装另一个):

 // 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')); 

现在我的日志文件看起来有组织(更好,但可以parsing):

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

使用以下命令创build一个文件:

 var log = console.log; console.log = function(){ log.apply(console, [Date.now()].concat(arguments)); }; 

在logging任何东西之前,在你的应用程序中要求 如果需要,对console.error执行相同的操作。

请注意,如果您使用的是这种解决scheme,将会销毁variables插入( console.log("he%s", "y") // "hey" )。 如果你需要的话,只要先logging时间戳:

 log.call(console, Date.now()); log.apply(console, arguments); 

您也可以使用log-timestamp软件包。 这很简单,也可以定制。

如果你想要一个没有其他外部依赖的解决scheme,但你想保持console.log(多个参数,variables插入)的全部function,你可以使用下面的代码:

 var log = console.log; console.log = function () { var first_parameter = arguments[0]; var other_parameters = Array.prototype.slice.call(arguments, 1); function formatConsoleDate (date) { var hour = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); var milliseconds = date.getMilliseconds(); return '[' + ((hour < 10) ? '0' + hour: hour) + ':' + ((minutes < 10) ? '0' + minutes: minutes) + ':' + ((seconds < 10) ? '0' + seconds: seconds) + '.' + ('00' + milliseconds).slice(-3) + '] '; } log.apply(console, [formatConsoleDate(new Date()) + first_parameter].concat(other_parameters)); }; 

您可以修改formatConsoleDate函数来设置date的格式。

此代码只需要在主JavaScript文件的顶部写入一次。

console.log("he%s", "y")将打印这样的东西:

 [12:22:55.053] hey 

这不是一个直接的答案,但你有没有看过winston.js? 它有更多的日志logging选项,包括日志logging到JSON文件或数据库。 这些默认情况下总是有时间戳。 只是一个想法。

您可以使用https://nodejs.org/api/util.html中的函数;util.log