NodeJS 未将 POST 正文发布到 DataDog 日志

NodeJS not posting POST body to DataDog logs

我正在尝试将 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 中的日志如下所示:

从上面的代码片段来看,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, creating tokens here, and Datadog log pipeline parsing here

希望对您有所帮助!