You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需Datadog Agent将Node.js日志发送至Datadog

无需Datadog Agent的Node.js日志集成方案

如果你不想依赖Datadog Agent,以下几种方案可以直接把Node.js应用日志发送到Datadog,实现完整的日志监控与分析:

1. 官方Winston/Morgan传输插件

Datadog提供了适配Node.js主流日志库的官方传输插件,无需Agent,直接通过HTTPS将日志发送到Datadog日志API。以Winston为例:

步骤:

  1. 安装依赖
npm install winston @datadog/winston-transport
  1. 配置日志实例
const winston = require('winston');
const { DatadogTransport } = require('@datadog/winston-transport');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(), // 推荐用JSON结构化日志
  transports: [
    new DatadogTransport({
      apiKey: process.env.DATADOG_API_KEY, // 用环境变量存储密钥,避免硬编码
      site: 'datadoghq.com', // 欧盟区账号替换为datadoghq.eu
      service: 'your-node-service', // 你的服务名称
      host: 'your-host-identifier', // 主机标识,方便排查问题
      source: 'node.js', // 日志来源标识
      batchInterval: 5000, // 批量发送间隔(毫秒),减少API请求次数
    }),
  ],
});

// 测试发送日志
logger.info('User authentication succeeded', { userId: 123, timestamp: new Date().toISOString() });

这个方案的优势是官方维护、配置简单,支持自动关联服务元数据,日志格式完全兼容Datadog的分析功能。

2. 直接调用Datadog日志API

如果不需要依赖日志框架,可以直接通过HTTP请求发送日志,灵活性最高:

步骤:

  1. 安装HTTP客户端(以axios为例)
npm install axios
  1. 封装日志发送函数
const axios = require('axios');

async function sendDatadogLog(logPayload) {
  const apiEndpoint = 'https://http-intake.logs.datadoghq.com/v1/input'; // 欧盟区替换为https://http-intake.logs.datadoghq.eu/v1/input
  const apiKey = process.env.DATADOG_API_KEY;

  try {
    await axios.post(apiEndpoint, logPayload, {
      headers: {
        'DD-API-KEY': apiKey,
        'Content-Type': 'application/json',
      },
    });
  } catch (error) {
    console.error('Failed to send log to Datadog:', error.response?.data || error.message);
  }
}

// 发送结构化日志
sendDatadogLog({
  message: 'Payment completed successfully',
  service: 'payment-service',
  host: 'payment-worker-01',
  level: 'info',
  attributes: {
    transactionId: 'txn_789456',
    amount: 149.99,
    currency: 'EUR'
  }
});

注意:建议实现批量发送逻辑,比如收集100条日志或间隔10秒发送一次,避免频繁请求导致API限流。

3. Pino日志库的Datadog传输插件

如果你的应用使用Pino(高性能Node.js日志库),可以用官方维护的@pinojs/pino-datadog插件:

步骤:

  1. 安装依赖
npm install pino @pinojs/pino-datadog
  1. 配置Pino实例
const pino = require('pino');

const logger = pino({
  level: 'info',
  transport: {
    target: '@pinojs/pino-datadog',
    options: {
      apiKey: process.env.DATADOG_API_KEY,
      service: 'high-traffic-node-service',
      host: 'service-host-02',
      ddVersion: '2.1.0', // 应用版本号
      batchSize: 20, // 批量发送的日志条数
      timeout: 5000, // 超时时间
    },
  },
});

logger.info('Order dispatched', { orderId: 456, customerId: 789 });

Pino的优势是性能出色,适合高并发场景,传输插件会自动处理日志批量发送和格式转换。

关键注意事项

  • 密钥安全:永远不要将Datadog API密钥硬编码到代码中,使用环境变量或密钥管理服务存储。
  • 结构化日志:优先使用JSON格式日志,Datadog会自动解析字段,支持过滤、聚合和创建监控告警。
  • 地区适配:根据你的Datadog账号所在地区选择对应的API端点,避免连接失败。
  • 错误处理:添加日志发送失败的降级逻辑(比如缓存本地日志后重试),避免丢失关键日志。

内容的提问来源于stack exchange,提问作者Jojo Joseph Kunathucherry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 23:47:38