application/logplex-1 的节点表达 body-parser

node express body-parser for application/logplex-1

我正在使用 node express 处理 POST 请求 heroku logging data with body data that is in the application/logplex-1 format (apparently syslog formatted).

特别是,我使用 body-parser module 作为中间件来解析 POST body。

指定app.use(bodyParser.text({ type: 'application/logplex-1' }))强制body-parser将body解析为文本可以正常工作,但文本只是一大块space-separated信息,没有太多除此以外的结构。因此我需要进一步解析 body 数据以找到并提取我想要的内容。

这没问题,但我想知道是否有更好的方法可以将 logplex-1 body 更直接地解析为更结构化且更易于使用的内容,例如 JSON。我不熟悉 logplex-1 或 syslog 格式,以及它是否确实有比我当前收到的文本块中明显更有用的东西 structure/metadata。

有什么想法吗?

我没有使用 logplex 或 Heroku 的经验,但这似乎有效:

var syslogParser = require('glossy').Parse;
var express      = require('express');
var app          = express();
var server       = app.listen(3012);

// Express allows arrays-of-middleware to act as a "single" middleware.
var logplexMiddleware = [
  // First, read the message body into `req.body`, making sure it only
  // accepts logplex "documents".
  require('body-parser').text({ type: 'application/logplex-1' }),
  // Next, split `req.body` into separate lines and parse each one using
  // the `glossy` syslog parser.
  function(req, res, next) {
    req.body = (req.body || '').split(/\r*\n/).filter(function(line) {
      // Make sure we only parse lines that aren't empty.
      return line.length !== 0;
    }).map(function(line) {
      // glossy doesn't like octet counts to be prepended to the log lines,
      // so remove those.
      return syslogParser.parse(line.replace(/^\d+\s+/, ''));
    });
    next();
  }
];

// Example endpoint:
app.post('/', logplexMiddleware, function(req, res) {
  console.log(req.body);
  return res.sendStatus(200);
});

它使用 glossy 将系统日志消息解析为 Javascript 个对象。

如果发布的数据量很大(> 数百 K),最好实施流式解决方案,因为上面的代码会首先将整个消息正文读入内存。