# NestJS LOG記錄和監控的實踐方式
提昇NestJS系統的穩運行嗎?🧐 瞭解適用於大型應用的有效日誌記錄和監控策略!🚀
## 日誌記錄和監控的重要性
大型 NestJS 系統,需要有效的log日誌記錄和監控功能,能夠藉由記錄及監控分析來追溯或防護:
* 及早檢測 bug 和性能問題。
* 跟蹤各application behavior行為。
* 確保平穩運作並減少停機時間。
LOG記錄為應用程式的日記,將監控視為其運行狀況追蹤。沒有這些,當出現問題時,就只能盲目的查詢Bug。如何保持系統正常運作,下列提供各項最佳實踐方式。
## 1. 使用日誌記錄Logging Library
NestJS 可透過 Logger 類提供內置的記錄系統。雖然它非常適合基本需求,但大型應用程式通常需要更高級的功能,例如日誌持久性、格式化和集中存儲。
範例:
```typescript
import { Logger } from '@nestjs/common';
@Injectable()
export class AppService {
private readonly logger = new Logger(AppService.name);
getHello(): string {
this.logger.log('Handling getHello request');
return 'Hello World!';
}
}
```
**對於大型應用程式:使用 Winston 或 Pino**
這些庫提供日誌級別、JSON 格式和外部集成等高級功能。
在 NestJS 中設置 Winston
安裝套件:
```bash
npm install winston nest-winston
```
設定 Winston:
```typescript
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
@Module({
imports: [
WinstonModule.forRoot({
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
}),
new winston.transports.File({ filename: 'logs/app.log' }),
],
}),
],
})
export class AppModule {}
```
## 2. 使用級別進行記錄
LOG應該講述一個事件。使用有意義的log level級別 (debug、info、warn、error) ,可以能夠針對問題狀況作追縱。
範例:向日誌添加log level
```typescript
this.logger.error('Database connection failed', 'DatabaseService');
```
## 3. Avoid Over-Logging 避免過度記錄
記錄每一個小細節可能會產生無數的日誌檔,會使追查更加困難。請遵循以下提示:
* 僅記錄基本資訊,例如 API 請求、資料庫查詢和錯誤。
* 使用不同的日誌級別,區分開發與運作中的環境與所屬的server。
## 4. 集中日誌
對於大型應用程式,本地日誌檔是不夠的。使用 ELK Stack(Elasticsearch、Logstash、Kibana) 或 LogDNA 等集中式日誌記錄工具。
將 ELK Stack 與 NestJS 集成,使用 Winston 將紀錄發送到 Elasticsearch:
```typescript
import Elasticsearch from 'winston-elasticsearch';
const esTransport = new Elasticsearch({
level: 'info',
clientOpts: { node: 'http://localhost:9200' },
});
winston.add(esTransport);
```
Elasticsearch可以在 Kibana 中分析和可視化日誌,以獲得更好統計分析。
## 5. 監控運作狀況
監控可確保系統運作狀況。Prometheus、Grafana 或 New Relic 等工具在 NestJS皆可以搭配運作 。
使用 @nestjs/terminus 軟監控系統運行作
```bash
npm install @nestjs/terminus
```
執行狀況檢查:
```typescript
import { TerminusModule } from '@nestjs/terminus';
import { HttpModule } from '@nestjs/axios';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
imports: [TerminusModule, HttpModule],
controllers: [AppController],
})
export class AppModule {}
```
使用GET檢查執行狀況:
```typescript
@Controller('health')
export class AppController {
@Get()
healthCheck(): string {
return 'OK';
}
}
```
## 6. 監控性能指標
使用 APM (Application Performance Monitoring) 工具跟蹤API回應時間、記憶體使用方式和資料庫查詢性能。
APM 工具
* Datadog
* New Relic
* AppSignal
範例:將 Datadog 與 NestJS 結合使用
安裝 Datadog 的 APM 代理:
```bash
npm install dd-trace
```
main.ts系統初始化設定:
```typescript
import 'dd-trace/init';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
```
## 7. 警告通知 Alerts and Notifications
設置Alerts以通知您的團隊有關關鍵問題的資訊。例如:
* 使用 Slack 或 PagerDuty 獲取即時錯誤Alerts。
* 配置 AWS CloudWatch 以接收自動通知。
範例:使用 Slack 發送警報
使用類似 node-slack-sdk 的庫將日誌警報發送到 Slack 通道。
```typescript
import { WebClient } from '@slack/web-api';
const slack = new WebClient('SLACK_TOKEN');
slack.chat.postMessage({
channel: '#alerts',
text: 'Critical error in production!',
});
```
## 8. 持續改進日誌記錄和監控
定期查看日誌和監控控制面板:
* 要刪除的冗長和無用的日誌。
* 依class level作風險評估。
## 結論
有效的日誌記錄和監控是任何大型 NestJS 系統需俱備的功能。可以及早發現錯誤,還可以確保系統應用程式在server環境的性能。通過遵循上述做法(例如使用高級日誌記錄工具、監控運行狀況和性能以及集中日誌),可以讓系統應用程式更加健壯、可擴展且更易於維護。
>出處來源:
>https://medium.com/@mohantaankit2002/best-practices-for-logging-and-monitoring-in-large-nestjs-applications-ae6e2ed31d93