Sails.js如何实现HTTP请求日志记录

23

由于Sails.js默认的日志记录不显示http请求日志(即使在详细模式下也是如此),因此最好的方法是将http请求日志记录到控制台,以便我可以看到是否存在格式错误的请求。 Expressjs的默认日志记录足够了。

如果可能的话,我更喜欢使用Sails.js的配置方式来实现它,而不是更改源代码的方法。

有没有人有这方面的经验?我的谷歌搜索似乎缺乏信息。

在Mac OSX上运行Sails v0.9.8。

4个回答

24

没有Sails配置选项可以记录每个请求,但是您可以在config/routes.js的顶部添加一个快速日志记录路由来解决这个问题:

// config/routes.js
'/*': function(req, res, next) {sails.log.verbose(req.method, req.url); next();}

1
如果您正在使用Sails v.011,则有一个配置选项。请参见Eagle的答案 - SyntaxRules
1
考虑到我写了那段代码,这一点是无可争议的 :) 实际上,如果您想记录 所有 HTTP 请求(包括静态资源),使用中间件是更好的选择。但它不会记录通过套接字进行的请求。 - sgress454

18

也许有些晚了,但是以后如果需要参考,我正在使用Sails 0.11,你可以在中间件中进行配置,在config/http.js文件中进行配置。

将以下函数添加到文件中(实际上是一个示例)

// Logs each request to the console
requestLogger: function (req, res, next) {
    console.log("Requested :: ", req.method, req.url);
    return next();
},

并将其设置在order变量上:

order: [
  'startRequestTimer',
  'cookieParser',
  'session',
  'requestLogger',  // Just here
  'bodyParser',
  'handleBodyParserError',
  'compress',
  'methodOverride',
  'poweredBy',
  '$custom',
  'router',
  'www',
  'favicon',
  '404',
  '500'
]

但是我找不到在中间件中使用我的 sails 日志记录器的方法。 - Jānis Gruzis
你能更好地解释一下问题吗?对我来说它完美地工作着。 - Eagle
1
如果只需使用console.log输出日志,则此解决方案可行。但是,如果我想要使用sails.log.*输出日志信息,则在中间件中无法访问sails,并且在我的漂亮的sails日志条目之间存在未格式化的console.log条目。我可以想象我可以手动加载记录器,但这很不方便。 - Jānis Gruzis
我该如何修改requestLogger函数,使其输出到文件而不是控制台? - Miek

3

我复制了sails-hook-requestlogger模块,将所有请求日志(访问日志)写入文件。

sails-hook-requestlogger-file

你只需要执行npm install sails-hook-requestlogger-file,就可以开始使用了!

用法

像平常一样启动你的应用程序,所有服务器请求都会被记录下来,并且有有用的信息,例如响应时间,直接输出到你的控制台。默认情况下,在开发环境中激活,在生产环境中停用。

配置

默认情况下,配置位于sails.config.requestloggerfile中。 你可以创建config/requestlogger.js并覆盖这些默认值:

Parameter        Type        Details
format           ((string))  Defines which logging format to use. Deaults to dev.
logLocation      ((string))  Defines where to log: console or file. Defaults to console.
fileLocation     ((string))  Location of file relative to project root (if file is specified in logLocation. This has no effect if console is specified in logLocation.
inDevelopment    ((boolean)) Whether or not to log requests in development environment. Defaults to true.
inProduction     ((boolean)) Whether or not to log requests in production environment Defaults to false.

示例 config/requestlogger.js 文件:

module.exports.requestloggerfile = {
 //see: https://github.com/expressjs/morgan#predefined-formats for more formats
  format: ':remote-addr - [:date[clf]] ":method :url" :status :response-time ms ":user-agent"',
  logLocation: 'file',
  fileLocation: '/var/log/myapp/access.log',
  inDevelopment: true,
  inProduction: true
};

希望能对某人有所帮助 :)

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接