Monitoring and metrics
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
You cannot fix what you cannot see. Follow one number from a shop's Python code to an engineer's phone: the app counts its failed requests, Prometheus pulls the count every 15 seconds and stores each reading in a time series, a query turns the counter's climb into errors per second, and when a bad release pushes that rate from 0.2 to 3 per second, an alerting rule fires and Alertmanager pages the on-call engineer. Then see the four golden signals worth watching first.
Watch the numbers
Monitoring means collecting numbers about a running service, called metrics, every few seconds. A tool stores them over time, draws graphs and wakes a person when a number crosses a line. Here Prometheus watches a shop's web app.
service → counts things in its code (metrics)
monitor → collects them every few seconds
→ stores them over time
→ graphs them, checks rules
person ← woken only when a rule tripsاقرأ الدرس خطوة بخطوة
Watch the numbers
Monitoring means collecting numbers about a running service, called metrics, every few seconds. A tool stores them over time, draws graphs and wakes a person when a number crosses a line. Here Prometheus watches a shop's web app.
service → counts things in its code (metrics) monitor → collects them every few seconds → stores them over time → graphs them, checks rules person ← woken only when a rule tripsCount inside the code
The app keeps its own numbers. Lines 1 to 3 use the prometheus_client library to make a counter: a metric that only goes up, and resets to zero when the app restarts. Its label, code, splits it by HTTP status, such as 200 or 500.
pip install prometheus-client import prometheus_client as prom reqs = prom.Counter('http_requests', 'Requests served', ['code']) counter only goes up (0 again on restart) gauge goes up and down histogram counts values into bucketsShow them on /metrics
Line 4 starts a small web server on port 8000. Its /metrics page lists every metric as plain text, one line per label value. Each failed request runs line 5, which adds one: the 500 line now reads 120.
GET http://localhost:8000/metrics # HELP http_requests_total Requests served # TYPE http_requests_total counter http_requests_total{code="200"} 5880.0 http_requests_total{code="500"} 120.0 the library adds _total to the namePrometheus pulls
Prometheus fetches the numbers itself. Every 15 seconds it requests /metrics and reads the reply; this is called a scrape. If a scrape fails, Prometheus sets a metric called up to 0 for that app, which can raise an alert too.
# prometheus.yml global: scrape_interval: 15s # default: 1m evaluation_interval: 15s scrape_configs: - job_name: shop static_configs: - targets: ['shop:8000'] up{job="shop"} 1 = scrape worked, 0 = failedA time series grows
Each scrape saves one sample, a time and a value. The samples for one metric name with one set of labels form a time series. After three scrapes, the 500 series holds 120, 123 and 126.
series http_requests_total{code="500"} t = 0 s 120 t = 15 s 123 t = 30 s 126 one name + one label set = one series code="200" is a different seriesThe rise per second
A counter's total means little; how fast it climbs matters. From 123 to 126 in 15 seconds is 3 ÷ 15 = 0.2 errors per second. PromQL, Prometheus's query language, works this out with rate().
(126 − 123) ÷ (30 s − 15 s) = 3 ÷ 15 = 0.2 errors per second PromQL: rate(http_requests_total{code="500"}[1m]) per-second rise, averaged over the last minuteA bad release
A new release breaks checkout. Line 5 now runs far more often, and the next two scrapes read 171 and 216: up 45 every 15 seconds, or 3 errors per second, fifteen times the normal rate.
t = 0 s 120 t = 15 s 123 +3 t = 30 s 126 +3 t = 45 s 171 +45 t = 60 s 216 +45 before 3 ÷ 15 = 0.2 /s after 45 ÷ 15 = 3 /s (× 15)The rule trips
An alerting rule checks rate > 1 per second every 15 seconds. It is true now, so the alert turns pending. Its for: 1m waits a whole minute; the rate is still high, so it fires. The wait ignores short blips.
groups: - name: shop rules: - alert: HighErrorRate expr: rate(http_requests_total{code="500"}[1m]) > 1 for: 1m ok → pending (true once) → firing (true for 1m)Page the on-call
Prometheus sends the firing alert to Alertmanager. It groups related alerts, drops duplicates and routes them, here by paging the on-call engineer's phone. A person now looks, and can roll the bad release back.
HighErrorRate firing → Alertmanager group related alerts in one message dedupe one page, not one per check route to the right receiver → page the on-call engineerWhat to measure
Google's SRE book names four golden signals to watch first. Latency, how long requests take, is usually a histogram. Traffic and errors are counters, as here. Saturation, how full the system is, is a gauge: a number that goes up and down.
four golden signals (Google SRE book) Latency how long requests take histogram Traffic how many requests come in counter Errors how many requests fail counter Saturation how full the system is gauge our errors counter is one of the four
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Which kind of metric should count failed requests?
A counter only increases, or resets to zero when the process restarts. You then look at how fast it rises. A gauge is for values that go up and down, such as memory in use.
02How does Prometheus get the numbers from the app?
Prometheus uses a pull model. Every scrape_interval (15 s here; the default is 1 minute) it sends an HTTP request to /metrics and stores what it reads. If the scrape fails, up is set to 0.
03The errors counter reads 123 at 15 s and 126 at 30 s. What is the error rate?
The rise is 126 − 123 = 3 over 15 seconds, so 3 ÷ 15 = 0.2 errors per second. PromQL's rate() works out this per-second rise over a whole window.
04An alerting rule has for: 1m. The condition becomes true. What happens next?
With a for clause the alert first goes pending. If the condition stays true for the whole duration it fires; a short blip that clears sooner never pages anyone.
05Which are Google's four golden signals?
The Google SRE book says that if you can only measure four things about a user-facing system, measure latency, traffic, errors and saturation.
المسرد
- Metric
- A number about a running system that is measured again and again, such as requests served or memory in use.
- Counter
- A metric that only goes up, or resets to zero when the process restarts. You usually look at its rate of increase.
- Gauge
- A metric that can go up and down, such as temperature, memory in use or queue length.
- Histogram
- A metric that counts observations, such as request durations, into buckets, so you can work out percentiles.
- Scrape
- One pull of a target's /metrics page by Prometheus, on a fixed interval.
- Time series
- The list of timestamped values for one metric name with one set of labels.
- PromQL
- Prometheus's query language. rate() turns a counter into a per-second rate of increase.
- Alertmanager
- The Prometheus component that receives firing alerts, groups and de-duplicates them, and routes them to email, chat or a pager.
الملاحظات والمصادر
- The figure divides one 15-second rise by 15 seconds; that is what irate() returns. rate() averages over its whole window, extrapolates to the window edges and handles counter resets, so on real data it gives about the same number, not exactly it. Alerts should use rate().
- Prometheus scrapes every minute unless told otherwise; its getting-started example sets 15 seconds, as here. Prometheus pulls, but short-lived batch jobs can push their numbers to a Pushgateway for it to scrape.
- The Python client adds _total to a counter's name, so Counter('http_requests', ...) appears as http_requests_total. It also exposes http_requests_created, the time the series started. The 200 line on the page is an invented example value.
- The sample values are an invented example. Real services usually alert on the share of requests that fail (errors divided by all requests), not on a raw count, so the threshold still makes sense as traffic grows.
- Kubernetes components emit metrics in the same Prometheus text format, on their own /metrics endpoints.
- The code card is real Python 3 and needs pip install prometheus-client. Run on its own it exits at once; in a real app the web server keeps it running and line 5 sits in the request handler.
- Prometheus docs: Overview
- Prometheus docs: Metric types
- Prometheus docs: Data model
- Prometheus docs: Jobs and instances (the up metric)
- Prometheus docs: Configuration (scrape_interval)
- Prometheus docs: Query functions (rate and irate)
- Prometheus docs: Alerting rules
- Prometheus docs: Alertmanager
- Prometheus docs: Exposition formats
- Prometheus Python client (prometheus_client)
- Kubernetes docs: Metrics for Kubernetes system components
- Google SRE book, ch. 6: Monitoring Distributed Systems (the four golden signals)
اختبار يتاح بعد الخطوة الأخيرة.