370 lines
8.3 KiB
Markdown
370 lines
8.3 KiB
Markdown
# Observabilité et Monitoring - Neah
|
|
|
|
Ce document décrit la stratégie d'observabilité pour Neah en production.
|
|
|
|
## Vue d'ensemble
|
|
|
|
L'observabilité comprend trois piliers:
|
|
- **Logs**: Enregistrement des événements et erreurs
|
|
- **Métriques**: Mesures de performance et santé du système
|
|
- **Traces**: Suivi des requêtes à travers le système
|
|
|
|
## 1. Logs
|
|
|
|
### 1.1 Logs Vercel
|
|
|
|
Vercel fournit des logs intégrés pour chaque déploiement:
|
|
|
|
**Accès:**
|
|
- Dashboard Vercel → Project → Deployments → [Déploiement] → Logs
|
|
- Ou via CLI: `vercel logs [deployment-url]`
|
|
|
|
**Types de logs:**
|
|
- Build logs: Erreurs de compilation
|
|
- Runtime logs: Erreurs d'exécution et logs applicatifs
|
|
- Edge logs: Logs des fonctions Edge
|
|
|
|
**Configuration:**
|
|
|
|
Les logs sont automatiquement collectés. Pour améliorer la visibilité:
|
|
|
|
```typescript
|
|
// lib/logger.ts (déjà présent dans le projet)
|
|
import { logger } from '@/lib/logger';
|
|
|
|
// Utilisation
|
|
logger.info('User logged in', { userId: user.id });
|
|
logger.error('Database connection failed', { error: error.message });
|
|
logger.warn('Rate limit approaching', { requests: count });
|
|
```
|
|
|
|
### 1.2 Logs PostgreSQL
|
|
|
|
**Via Docker:**
|
|
|
|
```bash
|
|
# Voir les logs PostgreSQL
|
|
docker logs neah-postgres-prod -f
|
|
|
|
# Logs avec timestamps
|
|
docker logs neah-postgres-prod --timestamps -f
|
|
```
|
|
|
|
**Configuration PostgreSQL pour les logs:**
|
|
|
|
Modifiez `docker-compose.prod.yml`:
|
|
|
|
```yaml
|
|
db:
|
|
environment:
|
|
POSTGRES_LOG_STATEMENT: "all" # ou "ddl", "mod", "none"
|
|
POSTGRES_LOG_DESTINATION: "stderr"
|
|
POSTGRES_LOG_TIMESTAMP: "on"
|
|
```
|
|
|
|
### 1.3 Centralisation des logs (Optionnel)
|
|
|
|
**Option A: Logtail (Recommandé pour Vercel)**
|
|
|
|
1. Créez un compte sur [Logtail](https://logtail.com)
|
|
2. Ajoutez l'intégration Vercel
|
|
3. Les logs Vercel seront automatiquement envoyés à Logtail
|
|
|
|
**Option B: Papertrail**
|
|
|
|
1. Créez un compte sur [Papertrail](https://papertrailapp.com)
|
|
2. Configurez un endpoint syslog
|
|
3. Redirigez les logs Docker vers Papertrail:
|
|
|
|
```yaml
|
|
# docker-compose.prod.yml
|
|
logging:
|
|
driver: "syslog"
|
|
options:
|
|
syslog-address: "tcp://logs.papertrailapp.com:XXXXX"
|
|
```
|
|
|
|
**Option C: Self-hosted (Loki + Grafana)**
|
|
|
|
Pour une solution auto-hébergée, utilisez Loki + Grafana:
|
|
|
|
```yaml
|
|
# docker-compose.prod.yml (ajout)
|
|
loki:
|
|
image: grafana/loki:latest
|
|
ports:
|
|
- "3100:3100"
|
|
volumes:
|
|
- loki_data:/loki
|
|
|
|
promtail:
|
|
image: grafana/promtail:latest
|
|
volumes:
|
|
- /var/lib/docker/containers:/var/lib/docker/containers:ro
|
|
- ./promtail-config.yml:/etc/promtail/config.yml
|
|
```
|
|
|
|
## 2. Métriques
|
|
|
|
### 2.1 Métriques Vercel
|
|
|
|
Vercel fournit des métriques intégrées:
|
|
|
|
- **Analytics**: Trafic, pages vues, temps de chargement
|
|
- **Speed Insights**: Core Web Vitals, temps de réponse
|
|
- **Web Vitals**: LCP, FID, CLS
|
|
|
|
**Activation:**
|
|
|
|
```bash
|
|
npm install @vercel/analytics @vercel/speed-insights
|
|
```
|
|
|
|
```typescript
|
|
// app/layout.tsx
|
|
import { Analytics } from '@vercel/analytics/react';
|
|
import { SpeedInsights } from '@vercel/speed-insights/next';
|
|
|
|
export default function RootLayout({ children }) {
|
|
return (
|
|
<html>
|
|
<body>
|
|
{children}
|
|
<Analytics />
|
|
<SpeedInsights />
|
|
</body>
|
|
</html>
|
|
);
|
|
}
|
|
```
|
|
|
|
### 2.2 Métriques PostgreSQL
|
|
|
|
**Via pg_stat_statements:**
|
|
|
|
```sql
|
|
-- Activer l'extension
|
|
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
|
|
|
|
-- Voir les requêtes les plus lentes
|
|
SELECT
|
|
query,
|
|
calls,
|
|
total_exec_time,
|
|
mean_exec_time,
|
|
max_exec_time
|
|
FROM pg_stat_statements
|
|
ORDER BY mean_exec_time DESC
|
|
LIMIT 10;
|
|
```
|
|
|
|
**Via Docker:**
|
|
|
|
```bash
|
|
# Statistiques du conteneur
|
|
docker stats neah-postgres-prod
|
|
|
|
# Métriques détaillées
|
|
docker exec neah-postgres-prod psql -U neah_prod_user -d calendar_db -c "
|
|
SELECT
|
|
datname,
|
|
numbackends,
|
|
xact_commit,
|
|
xact_rollback,
|
|
blks_read,
|
|
blks_hit,
|
|
tup_returned,
|
|
tup_fetched
|
|
FROM pg_stat_database
|
|
WHERE datname = 'calendar_db';
|
|
"
|
|
```
|
|
|
|
### 2.3 Métriques Redis
|
|
|
|
```bash
|
|
# Statistiques Redis
|
|
docker exec neah-redis-prod redis-cli INFO stats
|
|
|
|
# Mémoire utilisée
|
|
docker exec neah-redis-prod redis-cli INFO memory
|
|
|
|
# Commandes les plus utilisées
|
|
docker exec neah-redis-prod redis-cli INFO commandstats
|
|
```
|
|
|
|
### 2.4 Monitoring avec Prometheus (Optionnel)
|
|
|
|
Pour un monitoring avancé, utilisez Prometheus + Grafana:
|
|
|
|
```yaml
|
|
# docker-compose.prod.yml (ajout)
|
|
prometheus:
|
|
image: prom/prometheus:latest
|
|
volumes:
|
|
- ./prometheus.yml:/etc/prometheus/prometheus.yml
|
|
- prometheus_data:/prometheus
|
|
ports:
|
|
- "9090:9090"
|
|
|
|
grafana:
|
|
image: grafana/grafana:latest
|
|
ports:
|
|
- "3001:3000"
|
|
environment:
|
|
- GF_SECURITY_ADMIN_PASSWORD=admin
|
|
volumes:
|
|
- grafana_data:/var/lib/grafana
|
|
```
|
|
|
|
## 3. Alertes
|
|
|
|
### 3.1 Alertes Vercel
|
|
|
|
Vercel envoie automatiquement des alertes pour:
|
|
- Échecs de déploiement
|
|
- Erreurs critiques
|
|
- Dépassement de quotas
|
|
|
|
**Configuration:**
|
|
- Dashboard Vercel → Project → Settings → Notifications
|
|
|
|
### 3.2 Alertes personnalisées
|
|
|
|
**Option A: Sentry (Recommandé)**
|
|
|
|
Sentry fournit un suivi d'erreurs avancé:
|
|
|
|
```bash
|
|
npm install @sentry/nextjs
|
|
```
|
|
|
|
```bash
|
|
npx @sentry/wizard@latest -i nextjs
|
|
```
|
|
|
|
**Option B: Uptime Robot**
|
|
|
|
Pour surveiller la disponibilité:
|
|
1. Créez un compte sur [Uptime Robot](https://uptimerobot.com)
|
|
2. Ajoutez un monitor HTTP pour votre domaine Vercel
|
|
3. Configurez les alertes (email, Slack, etc.)
|
|
|
|
**Option C: Health Check Endpoint**
|
|
|
|
Créez un endpoint de santé:
|
|
|
|
```typescript
|
|
// app/api/health/route.ts
|
|
import { NextResponse } from 'next/server';
|
|
import { getRedisClient } from '@/lib/redis';
|
|
import { prisma } from '@/lib/prisma';
|
|
|
|
export async function GET() {
|
|
const checks = {
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
checks: {
|
|
database: 'unknown',
|
|
redis: 'unknown',
|
|
},
|
|
};
|
|
|
|
// Vérifier PostgreSQL
|
|
try {
|
|
await prisma.$queryRaw`SELECT 1`;
|
|
checks.checks.database = 'ok';
|
|
} catch (error) {
|
|
checks.checks.database = 'error';
|
|
checks.status = 'degraded';
|
|
}
|
|
|
|
// Vérifier Redis
|
|
try {
|
|
const redis = getRedisClient();
|
|
await redis.ping();
|
|
checks.checks.redis = 'ok';
|
|
} catch (error) {
|
|
checks.checks.redis = 'error';
|
|
checks.status = 'degraded';
|
|
}
|
|
|
|
const statusCode = checks.status === 'ok' ? 200 : 503;
|
|
return NextResponse.json(checks, { status: statusCode });
|
|
}
|
|
```
|
|
|
|
## 4. Dashboards
|
|
|
|
### 4.1 Dashboard Vercel
|
|
|
|
Le dashboard Vercel fournit:
|
|
- Vue d'ensemble des déploiements
|
|
- Analytics en temps réel
|
|
- Logs intégrés
|
|
|
|
### 4.2 Dashboard personnalisé (Grafana)
|
|
|
|
Si vous utilisez Prometheus + Grafana:
|
|
|
|
1. Créez un dashboard Grafana
|
|
2. Ajoutez des panels pour:
|
|
- Taux d'erreur HTTP
|
|
- Temps de réponse
|
|
- Utilisation de la base de données
|
|
- Utilisation de Redis
|
|
- Métriques applicatives
|
|
|
|
## 5. Bonnes pratiques
|
|
|
|
### 5.1 Logging
|
|
|
|
- **Niveau approprié**: Utilisez `info`, `warn`, `error` selon le contexte
|
|
- **Contexte structuré**: Ajoutez des métadonnées pertinentes
|
|
- **Pas de secrets**: Ne loguez jamais de mots de passe, tokens, etc.
|
|
- **Format cohérent**: Utilisez un format JSON structuré
|
|
|
|
```typescript
|
|
// ✅ Bon
|
|
logger.info('User created', {
|
|
userId: user.id,
|
|
email: user.email
|
|
});
|
|
|
|
// ❌ Mauvais
|
|
logger.info(`User created: ${user.password}`); // Ne jamais logger de secrets
|
|
```
|
|
|
|
### 5.2 Monitoring
|
|
|
|
- **Métriques clés**: Surveillez le taux d'erreur, latence, débit
|
|
- **Alertes pertinentes**: Configurez des alertes pour les problèmes critiques uniquement
|
|
- **SLIs/SLOs**: Définissez des objectifs de niveau de service
|
|
|
|
### 5.3 Performance
|
|
|
|
- **APM**: Utilisez un outil d'APM (Application Performance Monitoring)
|
|
- **Profiling**: Profilez régulièrement pour identifier les goulots d'étranglement
|
|
- **Optimisation**: Optimisez les requêtes lentes identifiées
|
|
|
|
## 6. Outils recommandés
|
|
|
|
| Outil | Usage | Coût |
|
|
|-------|-------|------|
|
|
| Vercel Analytics | Métriques intégrées | Gratuit (plan Hobby) |
|
|
| Sentry | Suivi d'erreurs | Gratuit (plan Developer) |
|
|
| Logtail | Centralisation logs | Payant |
|
|
| Uptime Robot | Monitoring uptime | Gratuit (50 monitors) |
|
|
| Grafana Cloud | Dashboards | Gratuit (limité) |
|
|
|
|
## 7. Checklist de mise en place
|
|
|
|
- [ ] Activer Vercel Analytics et Speed Insights
|
|
- [ ] Configurer Sentry pour le suivi d'erreurs
|
|
- [ ] Créer un endpoint `/api/health`
|
|
- [ ] Configurer les alertes Vercel
|
|
- [ ] Activer les logs PostgreSQL
|
|
- [ ] Configurer un service de centralisation de logs (optionnel)
|
|
- [ ] Créer des dashboards de monitoring (optionnel)
|
|
- [ ] Documenter les procédures d'alerte
|