Graylog: 在 Node.js 中使用

如何将 Node.js 日志发送到 Graylog

👋 欢迎使用 Stackhero 文档!

Stackhero 提供即用型 Graylog 云 解决方案,具有众多优势,包括:

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

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

从 Node.js 向 Graylog 发送日志非常简单。以下示例将演示如何使用 graylog2 包实现无缝日志传输。

首先,您可以通过以下命令安装该包:

npm install graylog2

以下是如何使用它记录日志消息的方法:

const graylog2 = require('graylog2');
const crypto = require('crypto');

const logger = new graylog2.graylog({
  servers: [{ host: '<XXXXXX>.stackhero-network.com', port: 12201 }] // 请确保将 "host" 替换为您的 Graylog 域名
});

// 向 Graylog 发送一条简单消息
logger.log('Simple message example');

// 向消息附加数据
logger.log(
  'Password recovery email', // 消息内容
  // 包含更多细节的 JSON 对象
  {
    subject: 'Password recovery',
    language: 'en_US',
    domain: 'gmail.com'
  }
);

// 高级示例
const ip = '1.2.3.4';
const ipHash = crypto.createHash('md5').update(ip).digest('hex');

const userId = '1234';
const userIdHash = crypto.createHash('md5').update(userId).digest('hex');

logger.log(
  'API request', // 消息内容
  // 包含更多细节的 JSON 对象
  {
    route: '/v1/messages/1234/',
    method: 'POST',

    responseTime: 12, // ms
    responseCode: 200,

    ipHash,
    userIdHash
  }
);

// 记录 Node.js 中未捕获的异常
process.on(
  'uncaughtException',
  err => {
    logger.log(
      err,
      { type: 'uncaughtException' }
    );
  }
);

如需更多示例,您可以访问 此 GitHub 仓库

warning 请勿忘记配置您的 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 输入(详见下文)。

在 Graylog 界面中,进入 System/Inputs,创建一个类型为 "GELF UDP" 的新输入,然后点击 "Launch new input"。在弹出的窗口中,勾选 "Global",填写标题,无需修改其他设置,直接确认。

就是这么简单!现在,您的 Graylog 已经可以接收来自 Node.js 应用的日志了。

为了提升安全性,建议限制允许向 12201 端口发送数据的 IP。您可以在 Stackhero 控制台中,选择您的 Graylog 服务,并在“Firewall”中仅允许您的 IP。