Skip to content

Gateway Observability

1. Tổng quan

Traefik cung cấp observability tích hợp sẵn qua Prometheus metrics, JSON access log có cấu trúc, và một dashboard thời gian thực. Không cần code tùy biến hay exporter bổ sung.

Nguồn: packages/gateway/config/traefik.yml (config metrics + access log), packages/gateway/config/dynamic/middlewares.yml (router dashboard), infrastructure/deployments/develop/monitoring/docker-compose.yml (Prometheus + Grafana)

2. Stack Observability

3. Prometheus Metrics

Cấu hình

Nguồn: packages/gateway/config/traefik.yml (dòng 37–43)

yaml
metrics:
  prometheus:
    entryPoint: traefik
    addEntryPointsLabels: true
    addRoutersLabels: true
    addServicesLabels: true

Entrypoint traefik lắng nghe trên :8080 nội bộ, ánh xạ tới host port 30100.

Cấu hình Scrape

Nguồn: infrastructure/deployments/develop/monitoring/config/prometheus/prometheus.yml

yaml
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: "traefik"
    static_configs:
      - targets: ["dev-nx-gateway:8080"]
        labels:
          instance: "gateway"

  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

Prometheus scrape metrics Traefik mỗi 15 giây qua mạng Docker (dev-nx-gateway:8080). Nó cũng giám sát chính nó tại localhost:9090.

Metrics có sẵn

MetricTypeMô tả
traefik_entrypoint_requests_totalCounterTổng request theo entrypoint
traefik_entrypoint_request_duration_secondsHistogramThời gian request theo entrypoint
traefik_router_requests_totalCounterTổng request theo router (service)
traefik_router_request_duration_secondsHistogramThời gian request theo router
traefik_service_requests_totalCounterTổng request theo dịch vụ backend
traefik_service_request_duration_secondsHistogramThời gian theo dịch vụ backend
traefik_service_open_connectionsGaugeKết nối đang mở hiện tại theo dịch vụ
traefik_service_server_upGaugeTrạng thái sức khỏe theo server backend (1=up, 0=down)

Ví dụ Truy vấn Prometheus

txt
# Tốc độ request theo dịch vụ (5 phút qua)
sum(rate(traefik_service_requests_total[5m])) by (service)

# Tỷ lệ lỗi (response 5xx)
sum(rate(traefik_service_requests_total{code=~"5.."}[5m]))
/ sum(rate(traefik_service_requests_total[5m]))

# P99 latency theo dịch vụ
histogram_quantile(0.99, rate(traefik_service_request_duration_seconds_bucket[5m]))

# Backend không khỏe
traefik_service_server_up == 0

4. Access Log có cấu trúc

Cấu hình

Nguồn: packages/gateway/config/traefik.yml (dòng 29–35)

yaml
accessLog:
  format: json
  fields:
    headers:
      names:
        Authorization: drop
        Cookie: drop

Định dạng Log

Mỗi request tạo một entry log JSON:

json
{
  "level": "info",
  "msg": "",
  "ClientAddr": "192.168.1.100:45678",
  "ClientHost": "192.168.1.100",
  "Duration": 145000000,
  "RequestMethod": "GET",
  "RequestPath": "/v1/api/commerce/products",
  "OriginStatus": 200,
  "ServiceName": "commerce@docker",
  "RouterName": "commerce@docker",
  "time": "2025-01-20T10:00:00Z"
}

Header nhạy cảm (Authorization, Cookie) được tự động bỏ khỏi output log.

App Logs

Nguồn: packages/gateway/config/traefik.yml (dòng 25–27)

yaml
log:
  level: INFO
  format: json

App log của Traefik (startup, thay đổi cấu hình, lỗi) cũng ở định dạng JSON ở mức INFO.

5. Traefik Dashboard

Cấu hình Tĩnh

Nguồn: packages/gateway/config/traefik.yml (dòng 7–8)

yaml
api:
  dashboard: true

Dashboard được bật nhưng KHÔNG phơi bày với api.insecure: true. Xác thực được xử lý bởi router file provider.

Router Dashboard

Nguồn: packages/gateway/config/dynamic/middlewares.yml (dòng 8–23)

yaml
http:
  routers:
    dashboard:
      rule: "PathPrefix(`/api`) || PathPrefix(`/dashboard`)"
      entryPoints:
        - traefik
      service: api@internal
      middlewares:
        - dashboard-auth
    dashboard-redirect:
      rule: "Path(`/`)"
      entryPoints:
        - traefik
      service: api@internal
      middlewares:
        - redirect-to-dashboard
        - dashboard-auth

Truy cập

Có sẵn tại http://localhost:30100 (ánh xạ từ port nội bộ 8080). Được bảo vệ bởi HTTP Basic Authentication (user: nx.eventry).

Dashboard Hiển thị

  • Tất cả router đã đăng ký và rule của chúng
  • Dịch vụ backend và trạng thái sức khỏe của chúng
  • Chuỗi middleware áp dụng cho mỗi router
  • Metrics request thời gian thực

6. Tích hợp Grafana

Cấu hình Container

Nguồn: infrastructure/deployments/develop/monitoring/docker-compose.yml

Thuộc tínhGiá trị
Imagegrafana/grafana:11.5.2
Host Port39300 (nội bộ :3000)
Admin Useradmin
Admin Passwordadmin
Sign UpTắt
Default Dashboardtraefik-overview.json

Data Source Prometheus

Nguồn: infrastructure/deployments/develop/monitoring/config/grafana/provisioning/datasources/prometheus.yml

yaml
datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://dev-nx-prometheus:9090
    isDefault: true
    editable: false

Provisioning Dashboard

Nguồn: infrastructure/deployments/develop/monitoring/config/grafana/provisioning/dashboards/dashboards.yml

yaml
providers:
  - name: "BANA"
    orgId: 1
    folder: "BANA"
    type: file
    disableDeletion: false
    editable: true
    options:
      path: /var/lib/grafana/dashboards
      foldersFromFilesStructure: false

Một dashboard traefik-overview.json được build sẵn được provisioning tự động tại infrastructure/deployments/develop/monitoring/config/grafana/dashboards/traefik-overview.json.

7. Cấu hình Container Prometheus

Nguồn: infrastructure/deployments/develop/monitoring/docker-compose.yml

Thuộc tínhGiá trị
Imageprom/prometheus:v3.2.1
Host Port39090 (nội bộ :9090)
Retention30 ngày (--storage.tsdb.retention.time=30d)
Lifecycle APIBật (--web.enable-lifecycle)
Config/etc/prometheus/prometheus.yml

8. Quy tắc Cảnh báo Khuyến nghị

Các quy tắc cảnh báo Prometheus sau được khuyến nghị cho giám sát production. Chúng chưa được triển khai hiện tại — thêm chúng vào một file quy tắc cảnh báo Prometheus khi sẵn sàng:

yaml
groups:
  - name: gateway
    rules:
      - alert: HighErrorRate
        expr: >
          sum(rate(traefik_service_requests_total{code=~"5.."}[5m]))
          / sum(rate(traefik_service_requests_total[5m])) > 0.05
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Tỷ lệ lỗi 5xx cao trên gateway"

      - alert: HighLatency
        expr: >
          histogram_quantile(0.99,
            rate(traefik_service_request_duration_seconds_bucket[5m])
          ) > 2
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "P99 latency vượt 2 giây"

      - alert: ServiceDown
        expr: traefik_service_server_up == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Dịch vụ backend {{ $labels.service }} bị down"

9. Trang liên quan

Tài liệuMô tả
Tổng quan GatewayThẻ định danh + service catalog
Vận hànhDeploy, runbook, phân loại cảnh báo
MiddlewaresĐịnh nghĩa middleware đầy đủ từ source
ResilienceTrạng thái circuit breaker, health check, retry
Quyết địnhADRs

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.