如何使用摩根记录器?

我不能与摩根登录。它不记录到控制台的信息。文档没有告诉如何使用它。

我想看看什么是变量,这是来自 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);
};

如何使用摩根?

171700 次浏览

看来你也和我一样,对这个问题感到困惑,这也是我无意中发现这个问题的原因。我认为我们把日志和手动日志联系起来,就像我们在 Java 中用 log4j (如果你知道 Java 的话)实例化一个 Logger 并说 log‘ this’一样。

然后我深入研究了摩根代码,发现它不是那种类型的日志记录器,它是用来自动记录请求、响应和相关数据的。当作为中间件添加到 Express/connect 应用程序时,默认情况下,它应该将语句记录到标准输出,显示远程 ip、请求方法、 http 版本、响应状态、用户代理等的详细信息。它允许您使用令牌修改日志,或者通过定义“ dev”为日志添加颜色,甚至可以注销到输出流(如文件)。

出于我们认为可以使用它的目的,就像在这个例子中,我们仍然必须使用:

console.log(..);

或者如果你想让输出对象更漂亮:

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

我想我有一种方法可以让你不能得到你想要的东西,但是你可以把 Morgan 的日志和 log4js 集成起来——换句话说,你所有的日志活动都可以到同一个地方。我希望这个来自 Express 服务器的摘要或多或少是不言自明的:

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

现在你可以写任何你想写的东西在 AppLog 上,Morgan 会把它想写的东西写到同一个地方,使用相同的附加物等等。当然,您可以在流包装器中调用 info ()或任何您喜欢的方式,而不是 debug ()——这只反映了您希望给予 Morgan 的 req/res 日志记录的日志记录级别。

Morgan 不应该用你描述的方式登录。Morgan 是按照 Apache 和 Nginx 等服务器登录 error _ log 或 access _ log 的方式来进行日志记录的。作为参考,你可以这样使用 Morgan:

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

请注意生产线,其中您看到使用选项 hash {skip: ..., stream: __dirname + '/../morgan.log'}调用 morgan

The stream property of that object determines where the logger outputs. By default it's STDOUT (your console, just like you want) but it'll only log request data. It isn't going to do what console.log() does.

如果你想在飞行中检查东西,可以使用内置的 util库:

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

所以你问题的答案是你问错了问题。但是如果您仍然希望使用 Morgan 来记录请求,那么就可以这样做了。

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

I faced the same problem ago and instead, I used winston. As fellas above said, morgan is for automated logging of request/response. Winston can be configured pretty much same way as log4Net/log4J, has severity levels, different streams to which you can log etc.

For example:

npm install winston

Then, if you call the below code somewhere on you application initialization:

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 是空的,即您还没有配置任何日志记录器。与 Log4Net/JXmlConfigure 方法非常相似——您需要首先调用它们,以初始化您的日志记录。

然后,以后在应用程序服务器端的任何地方都可以执行以下代码:

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

您可能需要尝试使用 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 i.e 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": ""
}


}

摩根:- Morgan 是一个中间件,可以帮助我们识别访问我们应用程序的客户端。

To Use Morgan, We need to follow below steps :-

  1. 使用以下命令安装 morgan:

npm install --save morgan

这将把 morgan 添加到 json.package 文件中

  1. Include the morgan in your project

var morgan = require('morgan');

3 >//创建一个写流(在追加模式下)

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

注: Make sure you do not plumb above blindly make sure you have every 你需要的条件。

一旦用户访问你的应用程序,上面的代码会自动创建一个 acces.log 文件到你的根目录。

就我而言:

-console.log()  // works
-console.error() // works
-app.use(logger('dev')) // Morgan is NOT logging requests that look like "GET /myURL 304 9.072 ms - -"

FIX: 我使用的是 VisualStudio 代码,我必须将其添加到我的 Launch Config 中

"outputCapture": "std"

建议,在从 IDE 运行时,直接从命令行运行以确保 IDE 没有导致问题。

利用 Morgan 很简单。正如 文件所建议的那样,有不同的方法可以从 Morgan 那里得到你想要的输出。它附带了预配置的日志记录方法,或者您可以自己定义一个。艾格。

要求(“摩根”)

app.use(morgan('tiny')

这会给你一个叫做 Tiny 的预配置,你会在你的终端中注意到它的作用。 In case you are not satisfied with this and you want deeper e.g. lets say the request url, then this is where tokens come in.

Token (‘ url’,function (req,res){ 返回’/api/myendpoint’ })

然后像这样使用它:

Use (morgan (’: url’)

检查文档,它全部突出显示在那里。

照我说的做:

app.use(morgan('tiny'));

会成功的。

根据文档,可以使用 预先定义好的方法记录请求数据

app.use(morgan('tiny'));

假设您想记录一个帖子请求数据,您可以创建一个 自定义标记并像这样使用它

morgan.token('postData', (request) => {
if (request.method == 'POST') return ' ' + JSON.stringify(request.body);
else return ' ';
});


app.use(
morgan(
':method :url :status :res[content-length] - :response-time ms :postData'
)
);

这将在控制台中将 POST 请求记录为

POST /api/test2 409 33 - 0.253 ms  {"name":"Test name","number":"323-322-55"}

注意 -不应该记录请求数据,因为它可能违反本地隐私法(例如欧盟的 GDPR)或业务标准。这只是个例子