Graylog: 使用 Winston GELF 包将 Node.js 日志发送到 Graylog

本文档属于在 Node.js 中使用指南的一部分。您可以在此处查看完整指南:如何将 Node.js 日志发送到 Graylog

👋 欢迎查阅 Stackhero 文档

Stackhero 提供全托管的 Graylog cloud 解决方案,专为高效与简便而设计。您可以:

  • 依赖于服务内置的无限制、专用 SMTP 邮件服务器
  • 只需一键即可轻松完成更新,无需手动操作。
  • 使用由HTTPS保护的自定义域名(例如 https://logs.your-company.com),为您的团队提供安全、直接的访问。
  • 专属私有基础设施上体验卓越的性能安全性,无共享资源,无干扰邻居。

专注于您的数据,而非工具本身:只需几分钟,即可开始使用 Stackhero 的 Graylog cloud hosting 解决方案。

warning 除非您的项目已经集成 Winston,否则建议优先使用 graylog2 包。如果已经使用 Winston,可以用 winston-gelf 替代。

要安装 Winston GELF 包,请运行:

npm install winston-gelf

如果您的项目尚未包含 Winston,可以通过以下命令添加:

npm install winston

以下是基础配置示例:

const winston = require('winston');
const winstonGelf = require('winston-gelf');
const process = require('process');

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winstonGelf({
      // 查看所有 gelfPro 选项:https://www.npmjs.com/package/gelf-pro
      gelfPro: {
        fields: {
          env: process.env.NODE_ENV || 'development'
        },
        adapterName: 'udp',
        adapterOptions: {
          host: '<XXXXXX>.stackhero-network.com', // 替换为您的 Graylog 域名
          port: 12201,
        }
      }
    })
  ]
});

// 信息日志示例
logger.info('This is a log information');

// 错误日志示例
try {
  throw Error('This is an example error');
}
catch(error) {
  logger.warn({ message: 'Error triggered', error });
}

请勿忘记配置您的 Graylog 输入(详见下文)。