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