【问题标题】:NodeJS not posting POST body to DataDog logsNodeJS 未将 POST 正文发布到 DataDog 日志
【发布时间】:2020-10-25 14:27:57
【问题描述】:

我正在尝试将 DataDog 与我的 NodeJS/Express 应用程序集成,但是当一个 POST 请求被发送到我的应用程序时,POST 的主体没有被传递给 datadog,我该如何解决这个问题?

我有一个名为 Winston.js 的文件,如下所示:

let appRoot = require('app-root-path');
let winston = require('winston');

// define the custom settings for each transport (file, console)
let options = {
    file: {
        level: 'info',
        filename: `${appRoot}/logs/app.log`,
        handleExceptions: true,
        json: true,
        maxsize: 52428800,
    },
    console: {
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

// instantiate a new Winston Logger with the settings defined above
let logger = winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
    write: function(message, encoding) {
        // use the 'info' log level so the output will be picked up by both transports (file and console)
        logger.info(message);
    },
};

module.exports = logger;

然后我使用以下方法将它们附加到我的应用程序中:

app.use(morgan('combined', { stream: winston.stream }));

目前我在 DataDog 中的日志如下所示:

【问题讨论】:

    标签: node.js datadog


    【解决方案1】:

    从上面的sn-ps看,combinedMorgan格式是直接发给Winston的,然后在Datadog的一个日志管道中解析。由于combined 格式不包含正文并且没有内置令牌,因此您必须使用带有自己令牌的自定义格式,然后相应地更新您的管道。

    例如,要在 Morgan 中创建包含状态代码和正文的自定义格式:

    morgan((tokens, req, res) => [
      tokens.status(req, res),
      req.body // assuming body-parser middleware is used
    ].join(' '))
    

    您还可以使用更简单的格式定义创建令牌以实现相同的结果:

    morgan.token('body', (req, res) => req.body
    morgan(':status :body')
    

    您可以找到有关自定义 Morgan 格式 here、创建令牌 here 和 Datadog 日志管道解析 here 的文档。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 2023-01-18
      • 2022-12-15
      • 2018-12-28
      • 2020-02-04
      • 2022-06-13
      • 2021-04-18
      相关资源
      最近更新 更多