node.js 为所有控制台消息添加时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18814221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding timestamps to all console messages
提问by Traveling Tech Guy
I have a complete, deployed, Express-based project, with many console.log() and console.error() statements throughout. The project runs using forever, directing the stdout and stderr to 2 separate files.
我有一个完整的、已部署的、基于 Express 的项目,其中包含许多 console.log() 和 console.error() 语句。该项目使用永远运行,将 stdout 和 stderr 定向到 2 个单独的文件。
It all works quite well, but now I'm missing timestamps - to know exactly when errors occurred.
一切都很好,但现在我缺少时间戳 - 确切知道错误发生的时间。
I can do some kind of search/replace throughout my code, or use some npm module that overrides console in each file, but I do not want to touch every model/route file, unless I absolutely have to.
我可以在我的代码中进行某种搜索/替换,或者使用一些覆盖每个文件中的控制台的 npm 模块,但我不想触及每个模型/路由文件,除非我绝对必须这样做。
Is there a way, perhaps an Express middleware, that would allow me to add a timestamp to every call made, or do I have to manually add it?
有没有办法,也许是 Express 中间件,可以让我为每次调用添加时间戳,还是必须手动添加?
回答by Traveling Tech Guy
It turns out, you canoverride the console functions at the top of the app.js file, and have it take effect in every other module. I got mixed results because one of my modules is forked as a child_process. Once I copied the line to the top of that file as well, all works.
事实证明,您可以覆盖 app.js 文件顶部的控制台功能,并使其在所有其他模块中生效。我得到了好坏参半的结果,因为我的一个模块被分叉为child_process. 一旦我将该行也复制到该文件的顶部,一切正常。
For the record, I installed the module console-stamp (npm install console-stamp --save), and added this line to the top of app.js and childProcess.js:
作为记录,我安装了模块 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]');
My problem now was that the :dateformat of the connect logger uses UTC format, rather than the one I'm using in the other console calls. That was easily fixed by registering my own time format (and as a side effect, requiring the dateformatmodule that console stampcomes with, rather than installing another one):
我现在的问题是:date连接记录器的格式使用 UTC 格式,而不是我在其他控制台调用中使用的格式。通过注册我自己的时间格式很容易解决这个问题(作为副作用,需要随附的dateformat模块console stamp,而不是安装另一个模块):
// 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'));
Now my log files look organized (and better yet, parseable):
现在我的日志文件看起来井井有条(更好的是,可解析):
[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
...
回答by Sunding Wei
module: "log-timestamp" works for me.
模块:“日志时间戳”对我有用。
see https://www.npmjs.com/package/log-timestamp
见 https://www.npmjs.com/package/log-timestamp
npm install log-timestamp
Simple to use
使用简单
console.log('Before log-timestamp');
require('log-timestamp');
console.log('After log-timestamp');
Result
结果
Before log-timestamp
[2012-08-23T20:08:32.000Z] After log-timestamp
回答by Andreas Hultgren
Create a file with the following:
使用以下内容创建文件:
var log = console.log;
console.log = function(){
log.apply(console, [Date.now()].concat(arguments));
};
Require it in your app before you log anything. Do the same for console.errorif needed.
在您记录任何内容之前,在您的应用程序中需要它。console.error如果需要,做同样的事情。
Note that this solution will destroy variable insertion (console.log("he%s", "y") // "hey") if you're using that. If you need that, just log the timestamp first:
请注意,console.log("he%s", "y") // "hey"如果您正在使用该解决方案,则该解决方案将破坏变量插入 ( )。如果需要,只需先记录时间戳:
log.call(console, Date.now());
log.apply(console, arguments);
回答by leszek.hanusz
If you want a solution without another external dependency but you want to keep the full functionalities of console.log (multiple parameters, variable insertion) you can use the following code:
如果您想要一个没有其他外部依赖的解决方案,但又想保留 console.log 的全部功能(多参数,变量插入),您可以使用以下代码:
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));
};
You can modify the formatConsoleDate function to format the date how you want.
您可以修改 formatConsoleDate 函数来格式化您想要的日期。
This code needs to be written only once on top of your main JavaScript file.
此代码只需在您的主 JavaScript 文件之上编写一次。
console.log("he%s", "y")will print something like this:
console.log("he%s", "y")将打印如下内容:
[12:22:55.053] hey
回答by Chetan
You could also use the log-timestamppackage. It's quite straightforward, and customizable as well.
您还可以使用log-timestamp包。它非常简单,也可以自定义。
回答by thxmxx
app.use(morgan('[:date[web]] :method :url :status :res[content-length] - :remote-addr - :response-time ms'))
回答by George Y.
This implementation is simple, supports original functionality of console.log (passing a single object, and variable substitution), doesn't use external modules and prints everything in a single call to console.log:
此实现很简单,支持 console.log 的原始功能(传递单个对象和变量替换),不使用外部模块并在对 console.log 的单个调用中打印所有内容:
var origlog = console.log;
console.log = function( obj, ...placeholders ){
if ( typeof obj === 'string' )
placeholders.unshift( Date.now() + " " + obj );
else
{
// This handles console.log( object )
placeholders.unshift( obj );
placeholders.unshift( Date.now() + " %j" );
}
origlog.apply( this, placeholders );
};
回答by Zeke Alexandre Nierenberg
This isn't a direct answer, but have you looked into winston.js? It has a ton more logging options including logging to a json file or database. These always have timestamps by default. Just a thought.
这不是一个直接的答案,但是您是否研究过 winston.js?它有更多的日志记录选项,包括记录到 json 文件或数据库。默认情况下,这些总是有时间戳。只是一个想法。
回答by mlosev
You can use a function util.logfrom https://nodejs.org/api/util.html.
您可以使用函数util.log从https://nodejs.org/api/util.html。
Be aware that it was deprecated since version 6.0.0.
请注意,它自 6.0.0 版以来已被弃用。
For higher versions you should "Use a third party module instead."
对于更高版本,您应该“改用第三方模块”。
回答by Shivam Shekhar
If you wish, you may create a custom logger for your application by extending the Node's build in "Console" class. Kindly refer to the following implementation
如果您愿意,您可以通过在“控制台”类中扩展节点的构建来为您的应用程序创建自定义记录器。请参考以下实现
"use strict";
const moment = require('moment');
const util = require('util');
const Console = require('console').Console;
class Logger extends Console {
constructor(stdout, stderr, ...otherArgs) {
super(stdout, stderr, ...otherArgs);
}
log(...args) {
super.log(moment().format('D MMM HH:mm:ss'), '-', util.format(...args));
}
error(...args) {
super.error(moment().format('D MMM HH:mm:ss'), '-', util.format(...args));
}
}
module.exports = (function() {
return new Logger(process.stdout, process.stderr);
}());
After that, you may use it in your code as :
之后,您可以在代码中使用它:
const logger = require('./logger');
logger.log('hello world', 123456);
logger.error('some error occurred', err);

