在Node.js應用程序中集成日志和錯誤追蹤系統是確保應用程序穩定性和可維護性的關鍵步驟。以下是一些流行的日志和錯誤追蹤系統的集成方法:
Winston是一個非常流行的Node.js日志庫,支持多種傳輸方式(如文件、控制臺、HTTP等)。
npm install winston
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console({
format: winston.format.simple()
})
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
Sentry是一個強大的錯誤追蹤平臺,可以幫助你實時監控和解決問題。
npm install @sentry/node
const Sentry = require('@sentry/node');
Sentry.init({
dsn: 'YOUR_SENTRY_DSN',
environment: process.env.NODE_ENV || 'development',
release: 'YOUR_RELEASE_VERSION'
});
process.on('uncaughtException', (event) => {
Sentry.captureException(event);
process.exit(1);
});
process.on('unhandledRejection', (event) => {
Sentry.captureException(event);
});
你可以將Winston和Sentry結合起來,以便在日志中記錄錯誤并發送到Sentry。
npm install winston @sentry/node
const winston = require('winston');
const Sentry = require('@sentry/node');
Sentry.init({
dsn: 'YOUR_SENTRY_DSN',
environment: process.env.NODE_ENV || 'development',
release: 'YOUR_RELEASE_VERSION'
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console({
format: winston.format.simple()
})
]
});
// 自定義Winston傳輸器以發送錯誤到Sentry
class SentryTransport extends winston.Transport {
constructor(opts) {
super(opts);
this.sentryClient = Sentry.Client();
}
log(info, callback) {
if (info.level === 'error') {
this.sentryClient.captureException(new Error(info.message));
}
callback();
}
}
logger.add(new SentryTransport({ level: 'error' }));
process.on('uncaughtException', (event) => {
logger.error(event);
Sentry.captureException(event);
process.exit(1);
});
process.on('unhandledRejection', (event) => {
logger.error(event);
Sentry.captureException(event);
});
通過集成Winston和Sentry,你可以有效地記錄日志并追蹤錯誤,從而提高應用程序的可靠性和可維護性。確保在生產環境中正確配置這些工具,并定期檢查日志和錯誤報告,以便及時發現和解決問題。