Chuyển đến nội dung

Bài 33 · Patterns and Deployment

Logging, Monitoring and Deployment

Operate a Discord or Telegram bot in production: structured JSON logs, counters and a metrics endpoint, throttled error alerts, a CI deploy pipeline and a go-live checklist.

Once real people use your bot, three questions matter every day: is it up, is it healthy, and what happened when something went wrong? Logging answers the third, metrics answer the second, and a repeatable deployment keeps the first true. This lesson builds the small tools for all three and ends with a go-live checklist.

Structured logs

console.log("user 5 ran ping") is fine on a laptop. In production you will search and filter thousands of lines, so write logs as one JSON object per line (JSON Lines). Every line has a time, a level, a message and fields you can filter on, such as chatId or command.

Node.js A small structured logger with levels and child context

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notes on good logging:

  • A child logger carries the request context (update ID, chat, user) so every line from one event can be found together.
  • Log events, not chatter: start, stop, command handled (with duration), API errors, rate limits, retries.
  • Never log message content in a bot that handles private chats unless you must; user text is personal data. Log the command name and IDs, and say in your privacy notice what you keep and for how long.
  • Write to standard output and let the platform (systemd journal, Docker, a log shipper) collect it. Do not manage log files by hand.

Metrics: numbers over time

Logs tell stories; metrics tell trends. Counters (commands handled, errors, API calls, 429 responses) and a few gauges (queue length, last successful poll) are enough to begin with. Expose them in the simple text format that Prometheus and many hosted tools understand.

Node.js Counters and a /metrics endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Keep label values to small fixed sets (command names, status codes). Never use a user ID or a chat ID as a label: a million users would create a million time series. Protect /metrics the same way as other internal endpoints, for example by listening on a private network or checking a token.

Useful alerts, in order of value: the bot has not polled or received an update for N minutes; error rate rises; 429 rate rises; restarts happen repeatedly; disk is nearly full (SQLite file or logs).

Telling a human about errors

Uncaught errors should reach you without flooding you. A common pattern is to send them to a private Telegram chat or Discord channel through a webhook, with throttling so a loop of identical errors produces one message, not a thousand.

Node.js Throttled error alerts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Deploying changes

A deployment should be boring and repeatable. A sensible minimal pipeline, shown read-only as a GitHub Actions file:

YAML
name: deploy
on:
  push:
    branches: [main]
jobs:
  test-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 24 }
      - run: npm ci
      - run: node --test
      - run: docker build -t registry.example.com/mybot:${{ github.sha }} .
      - run: docker push registry.example.com/mybot:${{ github.sha }}
      # then: ssh to the server and run "docker compose pull && docker compose up -d"

Principles that keep deployments safe:

  • Tests run before anything ships. A red build never deploys.
  • Images are tagged with the commit, so rollback means running the previous tag.
  • Database migrations (SQLite storage) run at startup, are small and are backward compatible with the previous version of the code where possible.
  • Secrets live on the server or in the platform's secret store, never in the pipeline file or image.
  • After a deploy, watch the logs and the health endpoint (hosting lesson) for a few minutes.

Go-live checklist

  • Token and secrets come from the environment; none are in Git history.
  • Bot has only the permissions and intents it needs.
  • Webhook secret or interaction signature verification is on.
  • Rate limiting, retries with backoff and a send queue exist.
  • Data is on a volume with a tested backup and restore.
  • Graceful shutdown and a supervisor restart policy are configured.
  • Logs are structured, secrets are redacted, errors alert a human.
  • A privacy text explains what you store and how users can delete it, with a /delete_my_data or similar command.
  • Platform rules were read: Discord's developer policy and Telegram's bot guidelines.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why log JSON lines instead of free text?

    Structured fields make logs queryable by tools.
  2. 2. What is wrong with using a user ID as a metrics label?

    High-cardinality labels explode the number of series; use small fixed sets like command names.
  3. 3. What is the purpose of throttling error alerts?

    One alert plus a count of suppressed duplicates is readable; a thousand identical alerts are not.
  4. 4. How do you roll back quickly if images are tagged with the commit SHA?

    Immutable, commit-tagged images make rollback a one-line change.

Summary

  • Write structured JSON logs with child context and automatic redaction; log events, not private message text.
  • Expose counters and gauges at /metrics; keep label sets small.
  • Alert on silence and error spikes, with throttling.
  • Deploy through tests, commit-tagged images and compatible migrations, and keep a go-live checklist.

Next: Project: a reminder bot

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.