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

本文件是在 Node.js 中使用指南的一部分。您可以在这里查看完整指南:如何将 Node.js 日志发送到 Graylog

👋 欢迎阅读 Stackhero 文档!

Stackhero 提供现成的 Graylog 云 解决方案,具有众多优势,包括:

  • 包含无限制和专用的 SMTP 电子邮件服务器
  • 只需点击即可轻松完成更新
  • 使用 HTTPS 保护的可定制域名(例如,https://logs.your-company.com)。
  • 专用私有 VM提供的最佳性能和强大安全性

节省时间简化您的生活:只需 5 分钟即可试用 Stackhero 的 Graylog 云托管 解决方案!

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 输入(详见下文)。