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 input(詳情見下方)。