node.js 如何使用摩根记录器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23494956/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:17:22  来源:igfitidea点击:

How to use Morgan logger?

node.jsloggingexpress

提问by Green

I cannot log with Morgan. It doesn't log info to console. The documentation doesn't tell how to use it.

我无法与摩根登录。它不会将信息记录到控制台。文档没有说明如何使用它。

I want to see what a variable is. This is a code from response.jsfile of expressjs framework:

我想看看变量是什么。这是来自response.jsexpressjs 框架文件的代码:

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

How to use Morgan?

如何使用摩根?

回答by NikhilWanpal

Seems you too are confused with the same thing as I was, the reason I stumbled upon this question. I think we associate logging with manual logging as we would do in Java with log4j (if you know java) where we instantiate a Logger and say log 'this'.

似乎你也和我一样对同一件事感到困惑,这就是我偶然发现这个问题的原因。我认为我们将日志记录与手动日志记录相关联,就像我们在 Java 中使用 log4j(如果您知道 java)所做的那样,我们实例化一个 Logger 并说 log 'this'。

Then I dug in morgan code, turns out it is not that type of a logger, it is for automated logging of requests, responses and related data. When added as a middleware to an express/connect app, by default it should log statements to stdout showing details of: remote ip, request method, http version, response status, user agent etc. It allows you to modify the log using tokens or add color to them by defining 'dev' or even logging out to an output stream, like a file.

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

For the purpose we thought we can use it, as in this case, we still have to use:

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

console.log(..);

Or if you want to make the output pretty for objects:

或者,如果您想让对象的输出更漂亮:

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

回答by mflo999

I think I have a way where you may not get exactly get what you want, but you can integrate Morgan's logging with log4js -- in other words, all your logging activity can go to the same place. I hope this digest from an Express server is more or less self-explanatory:

我想我有一种方法,您可能无法完全得到您想要的东西,但是您可以将 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);

Now you can write whatever you want to theAppLog and Morgan will write what it wants to the same place, using the same appenders etc etc. Of course, you can call info() or whatever you like in the stream wrapper instead of debug() -- that just reflects the logging level you want to give to Morgan's req/res logging.

现在你可以在 AppLog 中写任何你想要的东西,Morgan 会在同一个地方写它想要的东西,使用相同的 appender 等等。当然,你可以在流包装器中调用 info() 或任何你喜欢的东西,而不是 debug() -- 这仅反映了您想要为 Morgan 的 req/res 日志记录提供的日志记录级别。

回答by wgp

Morgan should not be used to log in the way you're describing. Morgan was built to do logging in the way that servers like Apache and Nginx log to the error_log or access_log. For reference, this is how you use morgan:

不应使用 Morgan 来按照您描述的方式登录。Morgan 被构建为以 Apache 和 Nginx 等服务器记录到 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'));
}

Note the production line where you see morgan called with an options hash {skip: ..., stream: __dirname + '/../morgan.log'}

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

The streamproperty 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.

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

If you want to inspect things on the fly use the built in utillibrary:

如果您想即时检查事物,请使用内置util库:

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

So the answer to your question is that you're asking the wrong question. But if you still want to use Morgan for logging requests, there you go.

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

回答by akrsmv

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.

我以前遇到过同样的问题,相反,我使用了 winston。如上所述,摩根用于自动记录请求/响应。Winston 的配置方式与 log4Net/log4J 几乎相同,具有严重性级别、可以记录的不同流等。

For example:

例如:

npm install winston

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

note: before calling above code, winston.loggers is empty, i.e you dont have any loggers configured yet. Pretty much like Log4Net/J XmlConfigure methods - you need to first call them, to init your logging.

注意:在调用上面的代码之前, winston.loggers 是空的,即你还没有配置任何记录器。非常像 Log4Net/J XmlConfigure 方法 - 您需要首先调用它们,以初始化您的日志记录。

Then, later wherever in you application server side code you may do:

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

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

Hope that helps.

希望有帮助。

for further documentation reference: https://www.npmjs.com/package/winston

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

回答by Sunil Verma

Morgan :- Morgan is a middleware which will help us to identify the clients who are accessing our application. Basically a logger.

Morgan :- Morgan 是一个中间件,它将帮助我们识别正在访问我们应用程序的客户。基本上是一个记录器。

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

要使用摩根,我们需要按照以下步骤操作:-

  1. Install the morgan using below command:
  1. 使用以下命令安装摩根:

npm install --save morgan

npm install --save morgan

This will add morgan to json.package file

这会将摩根添加到 json.package 文件

  1. Include the morgan in your project
  1. 在您的项目中包含摩根

var morgan = require('morgan');

var morgan = require('morgan');

3> // create a write stream (in append mode)

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

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

Note: Make sure you do not plumb above blindly make sure you have every conditions where you need .

注意:确保您不要盲目地在上面进行探测,确保您拥有所需的所有条件。

Above will automatically create a access.log file to your root once user will access your app.

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

回答by Carlos Ariza

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

example nodejs + express + morgan

示例 nodejs + express + morgan

回答by Sagan

In my case:

就我而言:

-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: I was using Visual Studio code, and I had to add this to my Launch Config

修复:我使用的是 Visual Studio 代码,我不得不将它添加到我的启动配置中

"outputCapture": "std"

Suggestion, in case you are running from an IDE, run directly from the command line to make sure the IDE is not causing the problem.

建议,如果您从 IDE 运行,请直接从命令行运行以确保 IDE 不会导致问题。

回答by Moe

Using morgan is pretty much straightforward. As the documentationsuggests, there are different ways to get your desired output with morgan. It comes with preconfigured logging methods or you can define one yourself. Eg.

使用摩根非常简单。正如文档所暗示的那样,有多种方法可以通过摩根获得您想要的输出。它带有预配置的日志记录方法,或者您可以自己定义一个。例如。

const morgan = require('morgan')

app.use(morgan('tiny')

const morgan = require('morgan')

app.use(morgan('tiny')

This will give you the preconfiguration called tiny. You will notice in your terminal what it does. 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.

这将为您提供名为 tiny 的预配置。您会在终端中注意到它的作用。如果您对此不满意并且想要更深入,例如让我们说请求 url,那么这就是令牌的用武之地。

morgan.token('url', function (req, res){ return '/api/myendpoint' })

morgan.token('url', function (req, res){ return '/api/myendpoint' })

then use it like so:

然后像这样使用它:

app.use(morgan(' :url ')

app.use(morgan(':url')

Check the documentation its all highlighted there.

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

回答by Gautam Anand

You might want to try using mongo-morgan-ext

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

The usage is:

用法是:

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

The expected output is

预期的输出是

{
    "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": ""
    }

}