如何使用Morganlogging器?

我无法login摩根。 它不会将信息logging到控制台。 该文档没有说明如何使用它。

我想看看一个variables是什么。 这是来自expressjs框架的response.js文件的代码:

 var logger = require("morgan"); res.render = function(view, options, fn){ options = options || {}; var self = this; var req = this.req; var app = req.app; // support callback function as second arg if ('function' == typeof options) { fn = options, options = {}; } // merge res.locals options._locals = self.locals; // default callback to respond fn = fn || function(err, str){ if (err) return req.next(err); self.send(str); }; // Here I want to see what fn is // But it doesn't show me anything in console // How to use it? logger(fn); // render app.render(view, options, fn); }; 

如何使用摩根?

看来你也是和我一样混淆了,就是我偶然发现了这个问题。 我认为我们将日志logging与手动日志logging相关联,就像我们在Java中使用log4j(如果您知道java)那样在实例化Logger并说日志“this”。

然后我在摩根代码中挖出来,结果发现它不是那种types的logging器,它是用来自动logging请求,响应和相关数据的。 当作为中间件添加到express / connect应用程序时,默认情况下它应该将语句logging到标准输出显示详细信息:远程ip,请求方法,http版本,响应状态,用户代理等。它允许您使用标记修改日志或通过定义'dev'或者甚至注销输出stream(比如文件)来为它们添加颜色。

为了我们的目的,我们认为我们可以使用它,因为在这种情况下,我们仍然必须使用:

 console.log(..); 

或者,如果你想为对象制作漂亮的输出:

 var util = require("util"); console.log(util.inspect(..)); 

我认为我有一种方法可以让你无法得到你想要的东西,但是你可以把Morgan的日志logging和log4js整合起来 – 换句话说,你所有的日志活动都可以到同一个地方。 我希望Express服务器的摘要或多或less是不言自明的:

 var express = require("express"); var log4js = require("log4js"); var morgan = require("morgan"); ... var theAppLog = log4js.getLogger(); var theHTTPLog = morgan({ "format": "default", "stream": { write: function(str) { theAppLog.debug(str); } } }); .... var theServer = express(); theServer.use(theHTTPLog); 

现在,你可以写任何你想要的应用程序日志和摩根会写什么想要在同一个地方,使用相同的appenders等等。当然,你可以调用信息()或任何你喜欢的stream包装,而不是debugging() – 这只是反映了你想要给摩根需求/资源logging的日志级别。

摩根不应该用你所描述的方式login。 Morganbuild立的方式是像Apache和Nginx这样的服务器login到error_log或access_log。 作为参考,这是你如何使用摩根:

 var express = require('express'), app = express(), morgan = require('morgan'); // Require morgan before use // You can set morgan to log differently depending on your environment if (app.get('env') == 'production') { app.use(morgan('common', { skip: function(req, res) { return res.statusCode < 400 }, stream: __dirname + '/../morgan.log' })); } else { app.use(morgan('dev')); } 

请注意您看到摩根用选项哈希{skip: ..., stream: __dirname + '/../morgan.log'}调用的生产线

该对象的stream属性决定了logging器输出的位置。 默认情况下,它是STDOUT(你的控制台,就像你想要的),但它只会logging请求数据。 它不会去做什么console.log()

如果你想在飞行中检查事情使用内置的util库:

 var util = require('util'); console.log(util.inspect(anyObject)); // Will give you more details than console.log 

所以你的问题的答案是你问错误的问题。 但是如果你仍然想用Morgan来logging请求,那么你就去。

 var express = require('express'); var fs = require('fs'); var morgan = require('morgan') var app = express(); // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(__dirname + '/access.log',{flags: 'a'}); // setup the logger app.use(morgan('combined', {stream: accessLogStream})) app.get('/', function (req, res) { res.send('hello, world!') }); 

例如nodejs + express + morgan

我以前面对同样的问题,而是用winston。 正如上面所说的那样,摩根是用来自动logging请求/响应的。 Winston的configuration方式可能与log4Net / log4J的configuration非常相似,具有严重级别,可以logging的不同stream。

例如:

npm install winston

然后,如果你在应用程序初始化的某个地方调用下面的代码:

 var winston = require('winston'); // setup default logger (no category) winston.loggers.add('default', { console: { colorize: 'true', handleExceptions: true, json: false, level: 'silly', label: 'default', }, file: { filename: 'some/path/where/the/log/file/reside/default.log', level: 'silly', json: false, handleExceptions: true, }, }); // // setup logger for category `usersessions` // you can define as many looggers as you like // winston.loggers.add('usersessions', { console: { level: 'silly', colorize: 'true', label: 'usersessions', json: false, handleExceptions: true, }, file: { filename: 'some/path/where/the/log/file/reside/usersessions.log', level: 'silly', json: false, handleExceptions: true, }, }); 

注意:在调用上面的代码之前,winston.loggers是空的,即你还没有configuration任何logging器。 非常像Log4Net / J XmlConfigure方法 – 您需要先调用它们,以启动您的日志logging。

然后,稍后在您的应用程序服务器端代码中,您可以执行以下操作:

 var winston = require('winston'); // log instances as defined in first snippet var defaultLog = winston.loggers.get('default'); var userSessionsLog = winston.loggers.get('usersessions'); defaultLog.info('this goes to file default.log'); userSessionsLog.debug('this goes to file usersessions.log') 

希望有所帮助。

进一步的文档参考: https : //www.npmjs.com/package/winston

摩根: – 摩根是一个中间件,它将帮助我们识别访问我们应用程序的客户。 基本上是一个logging器。

要使用摩根,我们需要遵循以下步骤:

  1. 使用下面的命令安装摩根:

npm install --save morgan

这将添加摩根到jason.package文件

  1. 包括摩根在你的项目

var morgan = require('morgan');

3> //创build一个写入stream(在附加模式下)

 var accessLogStream = fs.createWriteStream( path.join(__dirname, 'access.log'), {flags: 'a'} ); // setup the logger app.use(morgan('combined', {stream: accessLogStream})); 

注意:确保你不盲目地垂直,确保你有你需要的所有条件。

一旦用户访问您的应用程序,上面将自动创build一个access.log文件到您的根目录。

你可能想尝试使用mongo-morgan-ext

用法是:

 var logger = require('mongo-morgan-ext'); var db = 'mongodb://localhost:27017/MyDB'; var collection = 'Logs' var skipfunction = function(req, res) { return res.statusCode > 399; } //Thiw would skip if HTTP request response is less than 399 ie no errors. app.use(logger(db,collection,skipfunction)); //In your express-application 

预期的产出是

 { "RequestID": "", "status": "", "method": "", "Remote-user": "", "Remote-address": "", "URL": "", "HTTPversion": "", "Response-time": "", "date":"", "Referrer": "", "REQUEST": { //10 "Accept": "", "Accept-Charset": "", "Accept-Encoding": "", "Accept-Language": "", "Authorization": "", "Cache-Control": "", "Connection": "", "Cookie": "", "Content-Length": "", "Content-MD5": "", "Content-Type": "", "Expect": "", "Forwarded": "", "From": "", "Host": "", "Max-Forwards": "", "Origin": "", "Pragma": "", "Proxy-Authorization": "", "Range": "", "TE": "", "User-Agent": "", "Via": "", "Warning": "", "Upgrade": "", "Referer": "", "Date": "", "X-requested-with": "", "X-Csrf-Token": "", "X-UIDH": "", "Proxy-Connection": "", "X-Wap-Profile": "", "X-ATT-DeviceId": "", "X-Http-Method-Override":"", "Front-End-Https": "", "X-Forwarded-Proto": "", "X-Forwarded-Host": "", "X-Forwarded-For": "", "DNT": "", "Accept-Datetime": "", "If-Match": "", "If-Modified-Since": "", "If-None-Match": "", "If-Range": "", "If-Unmodified-Since": "" }, "RESPONSE": { "Status": "", "Content-MD5":"", "X-Frame-Options": "", "Accept-Ranges": "", "Age": "", "Allow": "", "Cache-Control": "", "Connection": "", "Content-Disposition": "", "Content-Encoding": "", "Content-Language": "", "Content-Length": "", "Content-Location": "", "Content-Range": "", "Content-Type":"", "Date":"", "Last-Modified": "", "Link": "", "Location": "", "P3P": "", "Pragma": "", "Proxy-Authenticate": "", "Public-Key-Pins": "", "Retry-After": "", "Server": "", "Trailer": "", "Transfer-Encoding": "", "TSV": "", "Upgrade": "", "Vary": "", "Via": "", "Warning": "", "WWW-Authenticate": "", "Expires": "", "Set-Cookie": "", "Strict-Transport-Security": "", "Refresh":"", "Access-Control-Allow-Origin": "", "X-XSS-Protection": "", "X-WebKit-CSP":"", "X-Content-Security-Policy": "", "Content-Security-Policy": "", "X-Content-Type-Options": "", "X-Powered-By": "", "X-UA-Compatible": "", "X-Content-Duration": "", "Upgrade-Insecure-Requests": "", "X-Request-ID": "", "ETag": "", "Accept-Patch": "" } }