Skip to contentমূল লেখায় যান

Topic 21 · DevOps & Cloudটপিক 21 · DevOps & Cloud

Monitoring and Observability

This page covers monitoring and observability: the three signals (metrics, logs, and traces), Prometheus and its rules, Alertmanager, Loki, and the trace context that OpenTelemetry passes between services. The practice run starts a small web app and the tools on your own machine. It needs no cloud account and no Docker. It comes after Ansible and before CNCF Projects: Build and Deliver.

56 min read56 মিনিটে পড়া যায় · 7 sections7টি সেকশন · 41 sources41টি সোর্স · updated Nov 2026আপডেট: Nov 2026

Scrape, store, query, alertস্ক্রেপ, জমা, কোয়েরি, অ্যালার্ট

Fail requests and watch a counter, a rate and an up metric change.অনুরোধ ব্যর্থ করুন আর দেখুন একটা counter, একটা rate আর একটা up metric কীভাবে বদলায়।

2 min2 মিনিট8 steps8টি ধাপ
  • Counterকাউন্টার0
  • Scrape everyস্ক্রেপ প্রতি5 s
Appঅ্যাপrunningচলছে/metrics/metrics পাতাPrometheusপ্রমিথিউসstoresজমা রাখেAlertঅ্যালার্টmanagerম্যানেজারcounter · app_requests_totalকাউন্টার · app_requests_total5 s5 s10 s10 s15 s15 s20 s20 s25 s25 s30 s30 s

You’ll learnআপনি শিখবেন

  • Prometheus pulls metrics on an intervalPrometheus নির্দিষ্ট বিরতিতে metric টেনে আনে
  • A counter only goes upকাউন্টার শুধু বাড়ে
  • Rate = change per secondরেট হলো সেকেন্ডে বদল
  • Error ratio = failing rate / total rateএরর অনুপাত = ব্যর্থ rate / মোট rate
  • up is 0 when the scrape failsscrape ব্যর্থ হলে up হয় 0

What it is

Observability. Observability lets you understand a system from the outside by letting you ask questions about that system without knowing its inner workings Source 1সোর্স 1. To ask those questions about your system, your application must be properly instrumented Source 1সোর্স 1. That is, the application code must emit signals such as traces, metrics, and logs Source 1সোর্স 1. Telemetry refers to data emitted from a system and its behavior Source 1সোর্স 1. OpenTelemetry is the mechanism by which application code is instrumented to help make a system observable Source 1সোর্স 1.

Monitoring. The Google SRE book describes monitoring as collecting, processing, aggregating, and displaying real-time quantitative data about a system, such as query counts and types, error counts and types, processing times, and server lifetimes Source 7সোর্স 7. White-box monitoring is based on metrics exposed by the internals of the system Source 7সোর্স 7. Black-box monitoring is testing externally visible behavior as a user would see it Source 7সোর্স 7.

The three signals. Metrics are aggregations over a period of time of numeric data about your infrastructure or application Source 1সোর্স 1. A log is a timestamped message emitted by services or other components Source 1সোর্স 1. A span represents a single unit of work or operation Source 1সোর্স 1. A trace is made of one or more spans Source 1সোর্স 1. The first span represents the root span Source 1সোর্স 1. A distributed trace records the path taken by a single request as it propagates through multiple services in an architecture Source 1সোর্স 1.

The tools of this page. Prometheus is an open-source systems monitoring and alerting toolkit Source 8সোর্স 8. It collects and stores its metrics as time series data Source 8সোর্স 8. The Alertmanager handles alerts sent by client applications such as the Prometheus server Source 23সোর্স 23. Loki is a horizontally-scalable, highly-available, multi-tenant log aggregation system inspired by Prometheus Source 31সোর্স 31. Unlike other logging systems, Loki does not index the contents of the logs Source 31সোর্স 31. OpenTelemetry is open source, and vendor- and tool-agnostic Source 2সোর্স 2. It is not an observability backend itself Source 2সোর্স 2.

সহজ English

Observability. Observability lets you understand a system from the outside by letting you ask questions about that system without knowing its inner workings Source 1সোর্স 1. To ask those questions about your system, your application must be properly instrumented Source 1সোর্স 1. That is, the application code must emit signals such as traces, metrics, and logs Source 1সোর্স 1. Telemetry refers to data emitted from a system and its behavior Source 1সোর্স 1. OpenTelemetry is the mechanism by which application code is instrumented to help make a system observable Source 1সোর্স 1.

Monitoring. The Google SRE book describes monitoring as collecting, processing, aggregating, and displaying real-time quantitative data about a system, such as query counts and types, error counts and types, processing times, and server lifetimes Source 7সোর্স 7. White-box monitoring is based on metrics exposed by the internals of the system Source 7সোর্স 7. Black-box monitoring is testing externally visible behavior as a user would see it Source 7সোর্স 7.

The three signals. Metrics are aggregations over a period of time of numeric data about your infrastructure or application Source 1সোর্স 1. A log is a timestamped message emitted by services or other components Source 1সোর্স 1. A span represents a single unit of work or operation Source 1সোর্স 1. A trace is made of one or more spans Source 1সোর্স 1. The first span represents the root span Source 1সোর্স 1. A distributed trace records the path taken by a single request as it propagates through multiple services in an architecture Source 1সোর্স 1.

The tools of this page. Prometheus is an open-source systems monitoring and alerting toolkit Source 8সোর্স 8. It collects and stores its metrics as time series data Source 8সোর্স 8. The Alertmanager handles alerts sent by client applications such as the Prometheus server Source 23সোর্স 23. Loki is a horizontally-scalable, highly-available, multi-tenant log aggregation system inspired by Prometheus Source 31সোর্স 31. Unlike other logging systems, Loki does not index the contents of the logs Source 31সোর্স 31. OpenTelemetry is open source, and vendor- and tool-agnostic Source 2সোর্স 2. It is not an observability backend itself Source 2সোর্স 2.

বাংলা ব্যাখ্যা

Observability। Observability আপনাকে একটা system বাইরে থেকে বুঝতে দেয়। ভেতরে কীভাবে কাজ হয় তা না জেনেও আপনি system সম্পর্কে প্রশ্ন করতে পারেন Source 1সোর্স 1। সেই প্রশ্ন করতে আপনার application-কে ঠিকমতো instrumented হতে হবে Source 1সোর্স 1। অর্থাৎ application code-কে trace, metric আর log-এর মতো signal ছাড়তে হবে Source 1সোর্স 1। Telemetry মানে একটা system আর তার আচরণ থেকে ছাড়া data Source 1সোর্স 1। OpenTelemetry হলো সেই প্রক্রিয়া, যার মাধ্যমে application code instrument করা হয়, যাতে system observable হয় Source 1সোর্স 1।

Monitoring। Google-এর SRE book monitoring-কে বর্ণনা করে একটা system সম্পর্কে real-time পরিমাণগত data সংগ্রহ, প্রক্রিয়াকরণ, একত্র করা আর দেখানো হিসেবে, যেমন query-র সংখ্যা ও ধরন, error-এর সংখ্যা ও ধরন, processing-এর সময় আর server-এর আয়ু Source 7সোর্স 7। White-box monitoring দাঁড়িয়ে আছে system-এর ভেতর থেকে প্রকাশ করা metric-এর ওপর Source 7সোর্স 7। Black-box monitoring হলো বাইরে থেকে দেখা আচরণ পরীক্ষা করা, যেভাবে একজন ব্যবহারকারী দেখবেন Source 7সোর্স 7।

তিনটা signal। Metric হলো একটা সময়ের মধ্যে আপনার infrastructure বা application-এর সংখ্যাভিত্তিক data-র সমষ্টি Source 1সোর্স 1। Log হলো service বা অন্য component-এর ছাড়া একটা timestamp-যুক্ত বার্তা Source 1সোর্স 1। Span হলো একটা একক কাজ বা operation Source 1সোর্স 1। একটা trace এক বা একাধিক span দিয়ে তৈরি Source 1সোর্স 1। প্রথম span হলো root span Source 1সোর্স 1। একটা distributed trace একটা অনুরোধের পথ নথিভুক্ত করে, যখন সেটা একটা architecture-এর একাধিক service-এর মধ্য দিয়ে যায় Source 1সোর্স 1।

এই page-এর tool। Prometheus হলো system monitoring ও alerting-এর একটা open-source toolkit Source 8সোর্স 8। সে তার metric time series data হিসেবে সংগ্রহ করে আর রাখে Source 8সোর্স 8। Alertmanager সেই alert সামলায়, যা Prometheus server-এর মতো client application পাঠায় Source 23সোর্স 23। Loki হলো Prometheus-এর অনুপ্রেরণায় তৈরি একটা horizontally-scalable, highly-available, multi-tenant log aggregation system Source 31সোর্স 31। অন্য logging system-এর মতো নয়, Loki log-এর বিষয়বস্তু index করে না Source 31সোর্স 31। OpenTelemetry open source, আর vendor ও tool নিরপেক্ষ Source 2সোর্স 2। সে নিজে কোনো observability backend নয় Source 2সোর্স 2।

How it works

The pieces of Prometheus. The Prometheus ecosystem consists of multiple components, many of which are optional Source 8সোর্স 8. The main Prometheus server scrapes and stores time series data Source 8সোর্স 8. Client libraries instrument application code Source 8সোর্স 8. An alertmanager handles alerts Source 8সোর্স 8. Prometheus scrapes metrics from instrumented jobs Source 8সোর্স 8. It stores all scraped samples locally and runs rules over this data to either aggregate and record new time series from existing data or generate alerts Source 8সোর্স 8. Grafana or other API consumers can be used to visualize the collected data Source 8সোর্স 8. Time series collection happens via a pull model over HTTP Source 8সোর্স 8.

The data model. Prometheus stores its data as time series Source 8সোর্স 8. Every time series is uniquely identified by its metric name and optional key-value pairs called labels Source 9সোর্স 9. Besides stored time series, Prometheus may generate temporary derived time series as the result of queries Source 9সোর্স 9.

Jobs, instances, and up. In Prometheus terms, an endpoint you can scrape is called an instance, usually corresponding to a single process Source 11সোর্স 11. A collection of instances with the same purpose is called a job Source 11সোর্স 11. When Prometheus scrapes a target, it attaches some labels automatically to the scraped time series Source 11সোর্স 11. The job label holds the configured job name that the target belongs to Source 11সোর্স 11. The instance label holds the host and port part of the target's URL that was scraped Source 11সোর্স 11. For each instance scrape, Prometheus stores a sample in the up series Source 11সোর্স 11. Its value is 1 if the instance is healthy, that is, reachable, or 0 if the scrape failed Source 11সোর্স 11. The up series is useful for instance availability monitoring Source 11সোর্স 11.

Metric types. The Prometheus instrumentation libraries offer four core metric types Source 10সোর্স 10. A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart Source 10সোর্স 10. Do not use a counter to expose a value that can decrease Source 10সোর্স 10. A gauge is a metric that represents a single numerical value that can arbitrarily go up and down Source 10সোর্স 10. A histogram records observations by counting them in configurable buckets Source 10সোর্স 10. It also provides a sum of all observed values Source 10সোর্স 10. A classic histogram consists of multiple time series of simple float samples Source 10সোর্স 10. They are the cumulative bucket counters, the sum, and the count Source 10সোর্স 10. Similar to a histogram, a summary samples observations Source 10সোর্স 10.

Histogram or summary. Summaries calculate streaming φ-quantiles within the instrumented program and expose them directly Source 20সোর্স 20. Histograms expose bucketed observation counts, and the calculation of quantiles happens on the Prometheus server using the histogram_quantile() function Source 20সোর্স 20. For a summary, other φ-quantiles and sliding windows cannot be calculated later Source 20সোর্স 20.

Names and labels. Metric names should have a single-word application prefix Source 18সোর্স 18. They should have a suffix that describes the unit, in plural form Source 18সোর্স 18. Every unique combination of key-value label pairs represents a new time series, which can dramatically increase the amount of data stored Source 18সোর্স 18. Do not use labels to store dimensions with high cardinality, such as user IDs, email addresses, or other unbounded sets of values Source 18সোর্স 18.

Instrumentation. For monitoring purposes, services can generally be broken down into three types: online-serving, offline-processing, and batch jobs Source 19সোর্স 19. Online-serving systems should be monitored on both the client and server side Source 19সোর্স 19. If the two sides see different behaviors, that is very useful information for debugging Source 19সোর্স 19. Time series that are not present until something happens are difficult to deal with Source 19সোর্স 19. To avoid this, export a default value such as 0 for any time series you know may exist in advance Source 19সোর্স 19.

The text format. As of Prometheus version 2.0, all processes that expose metrics to Prometheus must use a text format, by default Source 17সোর্স 17. Lines with a # as the first non-whitespace character are comments Source 17সোর্স 17. They are ignored unless the first token after # is either HELP or TYPE Source 17সোর্স 17. If the token is TYPE, exactly two more tokens are expected Source 17সোর্স 17. The first is the metric name, and the second is either counter, gauge, histogram, summary, or untyped Source 17সোর্স 17. The remaining lines describe samples, one per line Source 17সোর্স 17.

PromQL. Prometheus provides a functional query language called PromQL that lets the user select and aggregate time series data in real time Source 12সোর্স 12. A query request can be an instant query, evaluated at one point in time, or a range query at equally-spaced steps between a start and an end time Source 12সোর্স 12. An instant vector is a set of time series containing a single sample for each time series, all sharing the same timestamp Source 12সোর্স 12. A range vector is a set of time series containing a range of data points over time for each time series Source 12সোর্স 12. Instant vector selectors allow the selection of a set of time series and a single sample value for each at a given timestamp Source 12সোর্স 12. You can filter the series further with a comma-separated list of label matchers in curly braces Source 12সোর্স 12. By convention, time series that contain float counters have a name ending in _total Source 12সোর্স 12. Between an instant vector and a scalar, a comparison operator is applied to every sample, and the elements for which the comparison is false get dropped from the result Source 40সোর্স 40.

rate, aggregation, and quantiles. rate(v range-vector) calculates the per-second average rate of increase of the time series in the range vector Source 13সোর্স 13. Breaks in monotonicity, such as counter resets due to target restarts, are automatically adjusted for Source 13সোর্স 13. The rate function should only be used with counters Source 13সোর্স 13. Applying it to gauge floats will most likely produce a nonsensical result, but the query will be processed without complaints Source 12সোর্স 12. When you combine rate() with an aggregation operator such as sum(), always take a rate() first, then aggregate Source 13সোর্স 13. Otherwise rate() cannot detect counter resets when your target restarts Source 13সোর্স 13. histogram_quantile(φ scalar, b instant-vector) calculates the φ-quantile from a classic histogram or from a native histogram Source 13সোর্স 13. The page says to use the rate() function to specify the time window for the quantile calculation Source 13সোর্স 13. For classic histograms, the le label has to be included in the by clause Source 13সোর্স 13.

Recording rules and alerting rules. Recording rules allow you to precompute frequently needed or computationally expensive expressions and save their result as a new set of time series Source 14সোর্স 14. Recording and alerting rules exist in a rule group Source 14সোর্স 14. Rules within a group are run sequentially at a regular interval, with the same evaluation time Source 14সোর্স 14. The names of recording rules must be valid metric names Source 14সোর্স 14. For an alerting rule, all resultant time series of the expression become pending or firing alerts Source 14সোর্স 14. Alerts are considered firing once they have been returned for this long Source 14সোর্স 14. Alerts which have not yet fired for long enough are considered pending Source 14সোর্স 14. The labels clause allows specifying a set of additional labels to be attached to the alert Source 15সোর্স 15. The annotations clause specifies a set of informational labels that can be used to store longer additional information such as alert descriptions or runbook links Source 15সোর্স 15. For pending and firing alerts, Prometheus also stores synthetic time series of the form ALERTS Source 15সোর্স 15. Prometheus's alerting rules are good at figuring what is broken right now, but they are not a fully-fledged notification solution Source 15সোর্স 15.

Alertmanager. Alerting with Prometheus is separated into two parts Source 22সোর্স 22. Alerting rules in Prometheus servers send alerts to an Alertmanager Source 22সোর্স 22. The Alertmanager takes care of deduplicating, grouping, and routing them to the correct receiver integration Source 23সোর্স 23. Grouping categorizes alerts of similar nature into a single notification Source 23সোর্স 23. Inhibition is a concept of suppressing notifications for certain alerts if certain other alerts are already firing Source 23সোর্স 23. Silences are a straightforward way to simply mute alerts for a given time Source 23সোর্স 23. A silence is configured based on matchers, just like the routing tree Source 23সোর্স 23. Every alert enters the routing tree at the configured top-level route, which must match all alerts Source 24সোর্স 24. It then traverses the child nodes Source 24সোর্স 24. If continue is set to false, it stops after the first matching child Source 24সোর্স 24. If an alert does not match any children of a node, the alert is handled based on the configuration parameters of the current node Source 24সোর্স 24. Most optional parameters of a route are inherited from its parent node if not set Source 24সোর্স 24. The amtool command is a cli tool for interacting with the Alertmanager API Source 25সোর্স 25. It is bundled with all releases of Alertmanager Source 25সোর্স 25. The configuration page says that you can use amtool to validate that a configuration file is compatible with UTF-8 strict mode before enabling it in the server Source 24সোর্স 24. For that check, you do not need a running Alertmanager server Source 24সোর্স 24.

What to alert on. Aim to have as few alerts as possible, by alerting on symptoms that are associated with end-user pain rather than trying to catch every possible way that pain could be caused Source 21সোর্স 21. To summarize: keep alerting simple, alert on symptoms, have good consoles to allow pinpointing causes, and avoid having pages where there is nothing to do Source 21সোর্স 21. For error rates, page on user-visible errors Source 21সোর্স 21. The Google SRE book says that the four golden signals of monitoring are latency, traffic, errors, and saturation Source 7সোর্স 7. If you can only measure four metrics of your user-facing system, focus on these four Source 7সোর্স 7. Errors are the rate of requests that fail, either explicitly, implicitly, or by policy Source 7সোর্স 7. It is important to distinguish between the latency of successful requests and the latency of failed requests Source 7সোর্স 7.

Loki and its labels. Loki differs from Prometheus by focusing on logs instead of metrics, and collecting logs via push, instead of pull Source 31সোর্স 31. Labels allow Loki to organize and group together log messages into log streams Source 32সোর্স 32. If a service_name label is already present on the stream, Loki uses it directly Source 32সোর্স 32. Otherwise, Loki looks for the first non-empty value from a list of labels, in order Source 32সোর্স 32. If no label is found matching the list, a value of unknown_service is applied Source 32সোর্স 32. Use labels for things like regions, clusters, servers, applications, namespaces, and environments Source 33সোর্স 33. Too many label value combinations leads to too many streams Source 33সোর্স 33. The penalties for that in Loki are a large index and small chunks in the store, which in turn can actually reduce performance Source 33সোর্স 33. To avoid those issues, don’t add a label for something until you know you need it Source 33সোর্স 33.

LogQL. All LogQL queries contain a log stream selector Source 34সোর্স 34. Optionally, the log stream selector can be followed by a log pipeline Source 34সোর্স 34. A log pipeline is a set of stage expressions that are chained together and applied to the selected log streams Source 34সোর্স 34. The log stream selector is specified by one or more comma-separated key-value pairs Source 34সোর্স 34. The label matching operators are = (exactly equal), != (not equal), =~ (regex matches), and !~ (regex does not match) Source 34সোর্স 34. The line filter expression does a distributed grep over the aggregated logs from the matching log streams Source 34সোর্স 34. It searches the contents of the log line, discarding those lines that do not match the case-sensitive expression Source 34সোর্স 34. A label filter expression allows filtering log lines using their original and extracted labels Source 34সোর্স 34. Metric queries extend log queries by applying a function to log query results Source 35সোর্স 35. count_over_time(log-range) counts the entries for each log stream within the given range Source 35সোর্স 35.

The Loki HTTP API. When you use the push endpoint, you must send the timestamp as a string and not a number, otherwise the endpoint will return a 400 error Source 36সোর্স 36. The /loki/api/v1/query_range endpoint is used to do a query over a range of time Source 36সোর্স 36. Its limit parameter is the max number of entries to return, and it defaults to 100 Source 36সোর্স 36. Its start parameter defaults to one hour ago Source 36সোর্স 36. Query endpoints such as /loki/api/v1/query and /loki/api/v1/query_range return a set of statistics about the query execution Source 36সোর্স 36. The /ready endpoint returns HTTP 200 when the Loki instance is ready to accept traffic Source 36সোর্স 36. The /loki/api/v1/labels endpoint retrieves the list of known labels within a given time span Source 36সোর্স 36.

Traces and context propagation. With context propagation, signals (traces, metrics, and logs) can be correlated with each other, regardless of where they are generated Source 3সোর্স 3. Propagation is the mechanism that moves context between services and processes Source 3সোর্স 3. Propagation is usually handled by instrumentation libraries and is transparent to the user Source 3সোর্স 3. OpenTelemetry provides a text-based approach to propagate context to remote services using the W3C Trace Context HTTP headers Source 4সোর্স 4. The traceparent HTTP header field identifies the incoming request in a tracing system Source 6সোর্স 6. It has four fields: version, trace-id, parent-id, and trace-flags Source 6সোর্স 6. The trace-id is represented as a 16-byte array, and a value of all zero bytes is considered invalid Source 6সোর্স 6. The parent-id is represented as an 8-byte array, and a value of all zero bytes is considered invalid Source 6সোর্স 6. When the least significant bit of the flags is set, it denotes that the caller may have recorded trace data Source 6সোর্স 6. As this is a bit field, you cannot interpret flags by decoding the hex value and looking at the resulting number Source 6সোর্স 6. In Python, the sending service injects the current context Source 4সোর্স 4. The receiving service extracts context, for example from parsed HTTP headers, and then sets it as the current trace context Source 4সোর্স 4. The page says to use instrumentation libraries to propagate context Source 4সোর্স 4. The ConsoleSpanExporter is included in the opentelemetry-sdk package Source 5সোর্স 5.

Testing the monitoring itself. You can use promtool to test your rules Source 16সোর্স 16. The promtool check config command checks if the config files are valid or not Source 26সোর্স 26. The promtool check rules command checks if the rule files are valid or not Source 26সোর্স 26. The promtool test rules command runs unit tests for rules Source 26সোর্স 26. A test file has a list of rule files to consider for testing Source 16সোর্স 16. The input series use an expanding notation Source 16সোর্স 16. In it, _ represents a missing sample from scrape Source 16সোর্স 16. An alert test lists the union of all the firing alerts for the alertname under a single alert test case Source 16সোর্স 16. To test that an alerting rule is not firing, you can mention the fields and leave exp_alerts empty Source 16সোর্স 16. A test of a PromQL expression names the expression, the evaluation time, and the expected samples Source 16সোর্স 16.

সহজ English

The pieces of Prometheus. The Prometheus ecosystem consists of multiple components, many of which are optional Source 8সোর্স 8. The main Prometheus server scrapes and stores time series data Source 8সোর্স 8. Client libraries instrument application code Source 8সোর্স 8. An alertmanager handles alerts Source 8সোর্স 8. Prometheus scrapes metrics from instrumented jobs Source 8সোর্স 8. It stores all scraped samples locally and runs rules over this data to either aggregate and record new time series from existing data or generate alerts Source 8সোর্স 8. Grafana or other API consumers can be used to visualize the collected data Source 8সোর্স 8. Time series collection happens via a pull model over HTTP Source 8সোর্স 8.

The data model. Prometheus stores its data as time series Source 8সোর্স 8. Every time series is uniquely identified by its metric name and optional key-value pairs called labels Source 9সোর্স 9. Besides stored time series, Prometheus may generate temporary derived time series as the result of queries Source 9সোর্স 9.

Jobs, instances, and up. In Prometheus terms, an endpoint you can scrape is called an instance, usually corresponding to a single process Source 11সোর্স 11. A collection of instances with the same purpose is called a job Source 11সোর্স 11. When Prometheus scrapes a target, it attaches some labels automatically to the scraped time series Source 11সোর্স 11. The job label holds the configured job name that the target belongs to Source 11সোর্স 11. The instance label holds the host and port part of the target's URL that was scraped Source 11সোর্স 11. For each instance scrape, Prometheus stores a sample in the up series Source 11সোর্স 11. Its value is 1 if the instance is healthy, that is, reachable, or 0 if the scrape failed Source 11সোর্স 11. The up series is useful for instance availability monitoring Source 11সোর্স 11.

Metric types. The Prometheus instrumentation libraries offer four core metric types Source 10সোর্স 10. A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart Source 10সোর্স 10. Do not use a counter to expose a value that can decrease Source 10সোর্স 10. A gauge is a metric that represents a single numerical value that can arbitrarily go up and down Source 10সোর্স 10. A histogram records observations by counting them in configurable buckets Source 10সোর্স 10. It also provides a sum of all observed values Source 10সোর্স 10. A classic histogram consists of multiple time series of simple float samples Source 10সোর্স 10. They are the cumulative bucket counters, the sum, and the count Source 10সোর্স 10. Similar to a histogram, a summary samples observations Source 10সোর্স 10.

Histogram or summary. Summaries calculate streaming φ-quantiles within the instrumented program and expose them directly Source 20সোর্স 20. Histograms expose bucketed observation counts, and the calculation of quantiles happens on the Prometheus server using the histogram_quantile() function Source 20সোর্স 20. For a summary, other φ-quantiles and sliding windows cannot be calculated later Source 20সোর্স 20.

Names and labels. Metric names should have a single-word application prefix Source 18সোর্স 18. They should have a suffix that describes the unit, in plural form Source 18সোর্স 18. Every unique combination of key-value label pairs represents a new time series, which can dramatically increase the amount of data stored Source 18সোর্স 18. Do not use labels to store dimensions with high cardinality, such as user IDs, email addresses, or other unbounded sets of values Source 18সোর্স 18.

Instrumentation. For monitoring purposes, services can generally be broken down into three types: online-serving, offline-processing, and batch jobs Source 19সোর্স 19. Online-serving systems should be monitored on both the client and server side Source 19সোর্স 19. If the two sides see different behaviors, that is very useful information for debugging Source 19সোর্স 19. Time series that are not present until something happens are difficult to deal with Source 19সোর্স 19. To avoid this, export a default value such as 0 for any time series you know may exist in advance Source 19সোর্স 19.

The text format. As of Prometheus version 2.0, all processes that expose metrics to Prometheus must use a text format, by default Source 17সোর্স 17. Lines with a # as the first non-whitespace character are comments Source 17সোর্স 17. They are ignored unless the first token after # is either HELP or TYPE Source 17সোর্স 17. If the token is TYPE, exactly two more tokens are expected Source 17সোর্স 17. The first is the metric name, and the second is either counter, gauge, histogram, summary, or untyped Source 17সোর্স 17. The remaining lines describe samples, one per line Source 17সোর্স 17.

PromQL. Prometheus provides a functional query language called PromQL that lets the user select and aggregate time series data in real time Source 12সোর্স 12. A query request can be an instant query, evaluated at one point in time, or a range query at equally-spaced steps between a start and an end time Source 12সোর্স 12. An instant vector is a set of time series containing a single sample for each time series, all sharing the same timestamp Source 12সোর্স 12. A range vector is a set of time series containing a range of data points over time for each time series Source 12সোর্স 12. Instant vector selectors allow the selection of a set of time series and a single sample value for each at a given timestamp Source 12সোর্স 12. You can filter the series further with a comma-separated list of label matchers in curly braces Source 12সোর্স 12. By convention, time series that contain float counters have a name ending in _total Source 12সোর্স 12. Between an instant vector and a scalar, a comparison operator is applied to every sample, and the elements for which the comparison is false get dropped from the result Source 40সোর্স 40.

rate, aggregation, and quantiles. rate(v range-vector) calculates the per-second average rate of increase of the time series in the range vector Source 13সোর্স 13. Breaks in monotonicity, such as counter resets due to target restarts, are automatically adjusted for Source 13সোর্স 13. The rate function should only be used with counters Source 13সোর্স 13. Applying it to gauge floats will most likely produce a nonsensical result, but the query will be processed without complaints Source 12সোর্স 12. When you combine rate() with an aggregation operator such as sum(), always take a rate() first, then aggregate Source 13সোর্স 13. Otherwise rate() cannot detect counter resets when your target restarts Source 13সোর্স 13. histogram_quantile(φ scalar, b instant-vector) calculates the φ-quantile from a classic histogram or from a native histogram Source 13সোর্স 13. The page says to use the rate() function to specify the time window for the quantile calculation Source 13সোর্স 13. For classic histograms, the le label has to be included in the by clause Source 13সোর্স 13.

Recording rules and alerting rules. Recording rules allow you to precompute frequently needed or computationally expensive expressions and save their result as a new set of time series Source 14সোর্স 14. Recording and alerting rules exist in a rule group Source 14সোর্স 14. Rules within a group are run sequentially at a regular interval, with the same evaluation time Source 14সোর্স 14. The names of recording rules must be valid metric names Source 14সোর্স 14. For an alerting rule, all resultant time series of the expression become pending or firing alerts Source 14সোর্স 14. Alerts are considered firing once they have been returned for this long Source 14সোর্স 14. Alerts which have not yet fired for long enough are considered pending Source 14সোর্স 14. The labels clause allows specifying a set of additional labels to be attached to the alert Source 15সোর্স 15. The annotations clause specifies a set of informational labels that can be used to store longer additional information such as alert descriptions or runbook links Source 15সোর্স 15. For pending and firing alerts, Prometheus also stores synthetic time series of the form ALERTS Source 15সোর্স 15. Prometheus's alerting rules are good at figuring what is broken right now, but they are not a fully-fledged notification solution Source 15সোর্স 15.

Alertmanager. Alerting with Prometheus is separated into two parts Source 22সোর্স 22. Alerting rules in Prometheus servers send alerts to an Alertmanager Source 22সোর্স 22. The Alertmanager takes care of deduplicating, grouping, and routing them to the correct receiver integration Source 23সোর্স 23. Grouping categorizes alerts of similar nature into a single notification Source 23সোর্স 23. Inhibition is a concept of suppressing notifications for certain alerts if certain other alerts are already firing Source 23সোর্স 23. Silences are a straightforward way to simply mute alerts for a given time Source 23সোর্স 23. A silence is configured based on matchers, just like the routing tree Source 23সোর্স 23. Every alert enters the routing tree at the configured top-level route, which must match all alerts Source 24সোর্স 24. It then traverses the child nodes Source 24সোর্স 24. If continue is set to false, it stops after the first matching child Source 24সোর্স 24. If an alert does not match any children of a node, the alert is handled based on the configuration parameters of the current node Source 24সোর্স 24. Most optional parameters of a route are inherited from its parent node if not set Source 24সোর্স 24. The amtool command is a cli tool for interacting with the Alertmanager API Source 25সোর্স 25. It is bundled with all releases of Alertmanager Source 25সোর্স 25. The configuration page says that you can use amtool to validate that a configuration file is compatible with UTF-8 strict mode before enabling it in the server Source 24সোর্স 24. For that check, you do not need a running Alertmanager server Source 24সোর্স 24.

What to alert on. Aim to have as few alerts as possible, by alerting on symptoms that are associated with end-user pain rather than trying to catch every possible way that pain could be caused Source 21সোর্স 21. To summarize: keep alerting simple, alert on symptoms, have good consoles to allow pinpointing causes, and avoid having pages where there is nothing to do Source 21সোর্স 21. For error rates, page on user-visible errors Source 21সোর্স 21. The Google SRE book says that the four golden signals of monitoring are latency, traffic, errors, and saturation Source 7সোর্স 7. If you can only measure four metrics of your user-facing system, focus on these four Source 7সোর্স 7. Errors are the rate of requests that fail, either explicitly, implicitly, or by policy Source 7সোর্স 7. It is important to distinguish between the latency of successful requests and the latency of failed requests Source 7সোর্স 7.

Loki and its labels. Loki differs from Prometheus by focusing on logs instead of metrics, and collecting logs via push, instead of pull Source 31সোর্স 31. Labels allow Loki to organize and group together log messages into log streams Source 32সোর্স 32. If a service_name label is already present on the stream, Loki uses it directly Source 32সোর্স 32. Otherwise, Loki looks for the first non-empty value from a list of labels, in order Source 32সোর্স 32. If no label is found matching the list, a value of unknown_service is applied Source 32সোর্স 32. Use labels for things like regions, clusters, servers, applications, namespaces, and environments Source 33সোর্স 33. Too many label value combinations leads to too many streams Source 33সোর্স 33. The penalties for that in Loki are a large index and small chunks in the store, which in turn can actually reduce performance Source 33সোর্স 33. To avoid those issues, don’t add a label for something until you know you need it Source 33সোর্স 33.

LogQL. All LogQL queries contain a log stream selector Source 34সোর্স 34. Optionally, the log stream selector can be followed by a log pipeline Source 34সোর্স 34. A log pipeline is a set of stage expressions that are chained together and applied to the selected log streams Source 34সোর্স 34. The log stream selector is specified by one or more comma-separated key-value pairs Source 34সোর্স 34. The label matching operators are = (exactly equal), != (not equal), =~ (regex matches), and !~ (regex does not match) Source 34সোর্স 34. The line filter expression does a distributed grep over the aggregated logs from the matching log streams Source 34সোর্স 34. It searches the contents of the log line, discarding those lines that do not match the case-sensitive expression Source 34সোর্স 34. A label filter expression allows filtering log lines using their original and extracted labels Source 34সোর্স 34. Metric queries extend log queries by applying a function to log query results Source 35সোর্স 35. count_over_time(log-range) counts the entries for each log stream within the given range Source 35সোর্স 35.

The Loki HTTP API. When you use the push endpoint, you must send the timestamp as a string and not a number, otherwise the endpoint will return a 400 error Source 36সোর্স 36. The /loki/api/v1/query_range endpoint is used to do a query over a range of time Source 36সোর্স 36. Its limit parameter is the max number of entries to return, and it defaults to 100 Source 36সোর্স 36. Its start parameter defaults to one hour ago Source 36সোর্স 36. Query endpoints such as /loki/api/v1/query and /loki/api/v1/query_range return a set of statistics about the query execution Source 36সোর্স 36. The /ready endpoint returns HTTP 200 when the Loki instance is ready to accept traffic Source 36সোর্স 36. The /loki/api/v1/labels endpoint retrieves the list of known labels within a given time span Source 36সোর্স 36.

Traces and context propagation. With context propagation, signals (traces, metrics, and logs) can be correlated with each other, regardless of where they are generated Source 3সোর্স 3. Propagation is the mechanism that moves context between services and processes Source 3সোর্স 3. Propagation is usually handled by instrumentation libraries and is transparent to the user Source 3সোর্স 3. OpenTelemetry provides a text-based approach to propagate context to remote services using the W3C Trace Context HTTP headers Source 4সোর্স 4. The traceparent HTTP header field identifies the incoming request in a tracing system Source 6সোর্স 6. It has four fields: version, trace-id, parent-id, and trace-flags Source 6সোর্স 6. The trace-id is represented as a 16-byte array, and a value of all zero bytes is considered invalid Source 6সোর্স 6. The parent-id is represented as an 8-byte array, and a value of all zero bytes is considered invalid Source 6সোর্স 6. When the least significant bit of the flags is set, it denotes that the caller may have recorded trace data Source 6সোর্স 6. As this is a bit field, you cannot interpret flags by decoding the hex value and looking at the resulting number Source 6সোর্স 6. In Python, the sending service injects the current context Source 4সোর্স 4. The receiving service extracts context, for example from parsed HTTP headers, and then sets it as the current trace context Source 4সোর্স 4. The page says to use instrumentation libraries to propagate context Source 4সোর্স 4. The ConsoleSpanExporter is included in the opentelemetry-sdk package Source 5সোর্স 5.

Testing the monitoring itself. You can use promtool to test your rules Source 16সোর্স 16. The promtool check config command checks if the config files are valid or not Source 26সোর্স 26. The promtool check rules command checks if the rule files are valid or not Source 26সোর্স 26. The promtool test rules command runs unit tests for rules Source 26সোর্স 26. A test file has a list of rule files to consider for testing Source 16সোর্স 16. The input series use an expanding notation Source 16সোর্স 16. In it, _ represents a missing sample from scrape Source 16সোর্স 16. An alert test lists the union of all the firing alerts for the alertname under a single alert test case Source 16সোর্স 16. To test that an alerting rule is not firing, you can mention the fields and leave exp_alerts empty Source 16সোর্স 16. A test of a PromQL expression names the expression, the evaluation time, and the expected samples Source 16সোর্স 16.

বাংলা ব্যাখ্যা

Prometheus-এর অংশগুলো। Prometheus ecosystem-এ একাধিক component আছে, যার অনেকগুলো ঐচ্ছিক Source 8সোর্স 8। প্রধান Prometheus server time series data scrape করে আর রাখে Source 8সোর্স 8। client library application code instrument করে Source 8সোর্স 8। একটা alertmanager alert সামলায় Source 8সোর্স 8। Prometheus instrumented job থেকে metric scrape করে Source 8সোর্স 8। সে scrape করা সব sample স্থানীয়ভাবে রাখে, আর এই data-র ওপর rule চালায়, হয় বিদ্যমান data থেকে নতুন time series একত্র করে ও রেকর্ড করে, নয় alert তৈরি করে Source 8সোর্স 8। Grafana বা অন্য API consumer সংগৃহীত data দেখাতে ব্যবহার করা যায় Source 8সোর্স 8। time series সংগ্রহ হয় HTTP-র ওপর pull model-এ Source 8সোর্স 8।

Data model। Prometheus তার data রাখে time series হিসেবে Source 8সোর্স 8। প্রতিটা time series অনন্যভাবে চিহ্নিত হয় তার metric name আর label নামের ঐচ্ছিক key-value জোড়া দিয়ে Source 9সোর্স 9। সংরক্ষিত time series ছাড়াও Prometheus query-র ফল হিসেবে অস্থায়ী derived time series তৈরি করতে পারে Source 9সোর্স 9।

Job, instance আর up। Prometheus-এর ভাষায়, যে endpoint আপনি scrape করতে পারেন, তার নাম instance, যা সাধারণত একটা process-এর সঙ্গে মেলে Source 11সোর্স 11। একই উদ্দেশ্যের instance-এর একটা সংগ্রহের নাম job Source 11সোর্স 11। Prometheus একটা target scrape করলে scrape করা time series-এ নিজে থেকে কিছু label জুড়ে দেয় Source 11সোর্স 11। job label-এ থাকে target যে job-এর অন্তর্ভুক্ত, তার নাম Source 11সোর্স 11। instance label-এ থাকে scrape করা URL-এর host আর port অংশ Source 11সোর্স 11। প্রতিটা instance scrape-এর জন্য Prometheus up series-এ একটা sample রাখে Source 11সোর্স 11। instance সুস্থ, অর্থাৎ পৌঁছানো যায়, হলে তার মান 1, আর scrape ব্যর্থ হলে 0 Source 11সোর্স 11। up series instance-এর availability monitoring-এর জন্য কাজের Source 11সোর্স 11।

Metric-এর ধরন। Prometheus instrumentation library চারটা মূল metric type দেয় Source 10সোর্স 10। counter হলো একটা জমা হওয়া metric, যা একটাই একঘেয়েভাবে বাড়তে থাকা counter বোঝায়, যার মান শুধু বাড়তে পারে বা restart-এ শূন্যে ফিরতে পারে Source 10সোর্স 10। যে মান কমতে পারে, তা দেখাতে counter ব্যবহার করবেন না Source 10সোর্স 10। gauge হলো এমন metric, যা একটাই সংখ্যাগত মান বোঝায়, আর সেই মান ইচ্ছেমতো ওঠানামা করতে পারে Source 10সোর্স 10। histogram পর্যবেক্ষণ গোনে, সেগুলোকে বদলানো যায় এমন bucket-এ ফেলে Source 10সোর্স 10। সে পর্যবেক্ষণ করা সব মানের যোগফলও দেয় Source 10সোর্স 10। একটা classic histogram সরল float sample-এর একাধিক time series দিয়ে তৈরি Source 10সোর্স 10। সেগুলো হলো জমা হওয়া bucket counter, যোগফল আর গণনা Source 10সোর্স 10। histogram-এর মতোই, একটা summary পর্যবেক্ষণ নমুনা হিসেবে নেয় Source 10সোর্স 10।

Histogram না summary। summary instrumented program-এর ভেতরেই streaming φ-quantile হিসাব করে আর সরাসরি প্রকাশ করে Source 20সোর্স 20। histogram bucket করা পর্যবেক্ষণ-সংখ্যা প্রকাশ করে, আর quantile-এর হিসাব হয় Prometheus server-এ, histogram_quantile() function দিয়ে Source 20সোর্স 20। একটা summary-র ক্ষেত্রে অন্য φ-quantile আর sliding window পরে হিসাব করা যায় না Source 20সোর্স 20।

Name আর label। metric-এর নামে application-এর একটা এক-শব্দের prefix থাকা উচিত Source 18সোর্স 18। নামে একটা suffix থাকা উচিত, যা unit বর্ণনা করে, বহুবচনে Source 18সোর্স 18। key-value label জোড়ার প্রতিটা অনন্য সমন্বয় একটা নতুন time series বোঝায়, যা জমানো data-র পরিমাণ নাটকীয়ভাবে বাড়িয়ে দিতে পারে Source 18সোর্স 18। high cardinality-র dimension রাখতে label ব্যবহার করবেন না, যেমন user ID, email address, বা অন্য সীমাহীন মানের সেট Source 18সোর্স 18।

Instrumentation। monitoring-এর জন্য service-কে সাধারণত তিন ধরনে ভাগ করা যায়: online-serving, offline-processing আর batch job Source 19সোর্স 19। online-serving system-কে client আর server দুই দিকেই monitor করা উচিত Source 19সোর্স 19। দুই দিক আলাদা আচরণ দেখলে সেটা debugging-এর জন্য খুবই কাজের তথ্য Source 19সোর্স 19। যে time series কিছু ঘটার আগে থাকে না, তা সামলানো কঠিন Source 19সোর্স 19। এটা এড়াতে, যে time series আগে থেকেই থাকতে পারে বলে আপনি জানেন, তার জন্য 0-র মতো একটা default মান export করুন Source 19সোর্স 19।

Text format। Prometheus version 2.0 থেকে, Prometheus-এ metric প্রকাশ করা সব process-কে ডিফল্টভাবে একটা text format ব্যবহার করতেই হয় Source 17সোর্স 17। যে লাইনের প্রথম non-whitespace অক্ষর #, সে লাইন comment Source 17সোর্স 17। # -এর পরের প্রথম token HELP বা TYPE না হলে সেগুলো উপেক্ষা করা হয় Source 17সোর্স 17। token TYPE হলে ঠিক আরও দুটো token আশা করা হয় Source 17সোর্স 17। প্রথমটা metric-এর নাম, আর দ্বিতীয়টা counter, gauge, histogram, summary বা untyped-এর একটা Source 17সোর্স 17। বাকি লাইনগুলো sample বর্ণনা করে, প্রতি লাইনে একটা Source 17সোর্স 17।

PromQL। Prometheus একটা functional query language দেয়, যার নাম PromQL, আর যা ব্যবহারকারীকে real time-এ time series data বেছে নিতে ও একত্র করতে দেয় Source 12সোর্স 12। একটা query অনুরোধ হতে পারে instant query, যা একটা এক মুহূর্তে মূল্যায়ন হয়, বা range query, যা শুরু আর শেষ সময়ের মধ্যে সমান ব্যবধানের ধাপে চলে Source 12সোর্স 12। একটা instant vector হলো time series-এর একটা সেট, যাতে প্রতিটা time series-এ একটাই sample থাকে, আর সবার timestamp এক Source 12সোর্স 12। একটা range vector হলো time series-এর একটা সেট, যাতে প্রতিটা time series-এর জন্য সময় জুড়ে একটা data point-এর পরিসর থাকে Source 12সোর্স 12। Instant vector selector একটা নির্দিষ্ট timestamp-এ time series-এর একটা সেট আর প্রতিটার একটা sample মান বেছে নিতে দেয় Source 12সোর্স 12। আপনি curly brace-এর ভেতরে কমা দিয়ে আলাদা করা label matcher-এর একটা তালিকা জুড়ে series আরও ছেঁকে নিতে পারেন Source 12সোর্স 12। প্রচলিত রীতি অনুযায়ী, float counter ধরে রাখা time series-এর নাম _total দিয়ে শেষ হয় Source 12সোর্স 12। একটা instant vector আর একটা scalar-এর মধ্যে comparison operator প্রতিটা sample-এ প্রয়োগ হয়, আর যে element-এর তুলনার ফল false, সেগুলো result থেকে বাদ পড়ে Source 40সোর্স 40।

rate, aggregation আর quantile। rate(v range-vector) range vector-এর time series-এর প্রতি সেকেন্ডের গড় বৃদ্ধির হার হিসাব করে Source 13সোর্স 13। monotonicity-র ভাঙন, যেমন target restart-এর কারণে counter reset, নিজে থেকেই সমন্বয় করা হয় Source 13সোর্স 13। rate function শুধু counter-এর সঙ্গে ব্যবহার করা উচিত Source 13সোর্স 13। gauge float-এ এটা প্রয়োগ করলে খুব সম্ভব অর্থহীন ফল আসবে, কিন্তু query কোনো অভিযোগ ছাড়াই চলবে Source 12সোর্স 12। rate()-কে sum()-এর মতো aggregation operator-এর সঙ্গে মেলালে সবসময় আগে rate() নিন, তারপর aggregate করুন Source 13সোর্স 13। নইলে target restart হলে rate() counter reset ধরতে পারে না Source 13সোর্স 13। histogram_quantile(φ scalar, b instant-vector) একটা classic histogram বা native histogram থেকে φ-quantile হিসাব করে Source 13সোর্স 13। page বলে quantile হিসাবের সময়-জানালা ঠিক করতে rate() function ব্যবহার করতে Source 13সোর্স 13। classic histogram-এর ক্ষেত্রে le label-কে by clause-এ রাখতে হয় Source 13সোর্স 13।

Recording rule আর alerting rule। Recording rule আপনাকে প্রায়ই লাগে বা হিসাব করতে ভারী এমন expression আগে থেকে হিসাব করে তার ফল time series-এর একটা নতুন সেট হিসেবে রাখতে দেয় Source 14সোর্স 14। Recording আর alerting rule একটা rule group-এ থাকে Source 14সোর্স 14। একটা group-এর rule একই মূল্যায়ন-সময়ে, নিয়মিত ব্যবধানে, পরপর চলে Source 14সোর্স 14। recording rule-এর নাম অবশ্যই বৈধ metric name হতে হবে Source 14সোর্স 14। একটা alerting rule-এর expression-এর সব ফল time series pending বা firing alert হয়ে যায় Source 14সোর্স 14। alert firing ধরা হয়, একবার সেগুলো এই সময় ধরে ফেরত এলে Source 14সোর্স 14। যে alert এখনও যথেষ্ট সময় ধরে ফেরত আসেনি, সেগুলো pending ধরা হয় Source 14সোর্স 14। labels clause alert-এ জোড়া যাবে এমন অতিরিক্ত label-এর একটা সেট ঠিক করতে দেয় Source 15সোর্স 15। annotations clause তথ্যমূলক label-এর একটা সেট ঠিক করে, যা alert-এর বিবরণ বা runbook link-এর মতো দীর্ঘ অতিরিক্ত তথ্য রাখতে ব্যবহার করা যায় Source 15সোর্স 15। pending আর firing alert-এর জন্য Prometheus ALERTS আকারের কৃত্রিম time series-ও রাখে Source 15সোর্স 15। Prometheus-এর alerting rule এখন কী ভেঙেছে তা বের করতে ভালো, কিন্তু সেগুলো পূর্ণাঙ্গ notification সমাধান নয় Source 15সোর্স 15।

Alertmanager। Prometheus-এর alerting দুই ভাগে বিভক্ত Source 22সোর্স 22। Prometheus server-এর alerting rule একটা Alertmanager-এর কাছে alert পাঠায় Source 22সোর্স 22। Alertmanager সেই alert-গুলোর deduplication, grouping আর সঠিক receiver integration-এ routing সামলায় Source 23সোর্স 23। Grouping একই ধরনের alert-কে একটা notification-এ আনে Source 23সোর্স 23। Inhibition হলো কিছু alert আগে থেকেই firing থাকলে অন্য কিছু alert-এর notification চেপে দেওয়ার ধারণা Source 23সোর্স 23। Silence হলো কিছু সময়ের জন্য alert চুপ করিয়ে দেওয়ার সরল উপায় Source 23সোর্স 23। একটা silence ঠিক হয় matcher দিয়ে, routing tree-র মতোই Source 23সোর্স 23। প্রতিটা alert routing tree-তে ঢোকে সবচেয়ে ওপরের route দিয়ে, যাকে অবশ্যই সব alert-এর সঙ্গে মিলতে হবে Source 24সোর্স 24। তারপর সে child node-গুলো ঘুরে দেখে Source 24সোর্স 24। continue false হলে সে প্রথম মিলে যাওয়া child-এর পর থামে Source 24সোর্স 24। কোনো alert একটা node-এর কোনো child-এর সঙ্গে না মিললে alert-টা সামলানো হয় বর্তমান node-এর configuration parameter অনুযায়ী Source 24সোর্স 24। একটা route-এর বেশির ভাগ ঐচ্ছিক parameter, সেট না করলে, তার parent node থেকে পাওয়া যায় Source 24সোর্স 24। amtool হলো Alertmanager API-র সঙ্গে কাজ করার একটা cli tool Source 25সোর্স 25। এটা Alertmanager-এর সব release-এর সঙ্গে আসে Source 25সোর্স 25। configuration page বলে, server-এ চালু করার আগে একটা configuration file UTF-8 strict mode-এর সঙ্গে সামঞ্জস্যপূর্ণ কি না যাচাই করতে আপনি amtool ব্যবহার করতে পারেন Source 24সোর্স 24। সেই যাচাইয়ের জন্য একটা চালু Alertmanager server লাগে না Source 24সোর্স 24।

কীসের ওপর alert দেবেন। যত কম সম্ভব alert রাখার লক্ষ্য রাখুন, শেষ-ব্যবহারকারীর কষ্টের সঙ্গে জড়িত লক্ষণের ওপর alert দিয়ে, সেই কষ্ট যত উপায়ে হতে পারে তার সবটা ধরার চেষ্টা না করে Source 21সোর্স 21। সারসংক্ষেপে: alerting সরল রাখুন, লক্ষণের ওপর alert দিন, কারণ চিহ্নিত করতে ভালো console রাখুন, আর এমন page এড়ান যেখানে করার কিছু নেই Source 21সোর্স 21। error rate-এর ক্ষেত্রে ব্যবহারকারীর চোখে পড়ে এমন error-এ page করুন Source 21সোর্স 21। Google-এর SRE book বলে, monitoring-এর চারটা golden signal হলো latency, traffic, error আর saturation Source 7সোর্স 7। আপনার ব্যবহারকারীমুখী system-এর শুধু চারটা metric মাপতে পারলে এই চারটার ওপর মনোযোগ দিন Source 7সোর্স 7। Error হলো যে অনুরোধ ব্যর্থ হয় তার হার, প্রকাশ্যে, অপ্রকাশ্যে বা নীতির কারণে Source 7সোর্স 7। সফল অনুরোধের latency আর ব্যর্থ অনুরোধের latency আলাদা করে দেখা গুরুত্বপূর্ণ Source 7সোর্স 7।

Loki আর তার label। Loki Prometheus থেকে আলাদা, কারণ সে metric-এর বদলে log-এর ওপর মনোযোগ দেয়, আর log সংগ্রহ করে pull-এর বদলে push-এ Source 31সোর্স 31। Label Loki-কে log বার্তা সাজাতে আর log stream-এ একত্র করতে দেয় Source 32সোর্স 32। stream-এ আগে থেকে একটা service_name label থাকলে Loki সেটাই সরাসরি ব্যবহার করে Source 32সোর্স 32। নইলে Loki একটা label-তালিকা থেকে ক্রমানুসারে প্রথম ফাঁকা-নয় এমন মান খোঁজে Source 32সোর্স 32। তালিকার কোনো label না মিললে unknown_service মান বসানো হয় Source 32সোর্স 32। region, cluster, server, application, namespace আর environment-এর মতো জিনিসের জন্য label ব্যবহার করুন Source 33সোর্স 33। label-মানের অনেক বেশি সমন্বয় মানে অনেক বেশি stream Source 33সোর্স 33। Loki-তে এর শাস্তি হলো একটা বড় index আর store-এ ছোট chunk, যা আসলে performance কমিয়ে দিতে পারে Source 33সোর্স 33। সেই সমস্যা এড়াতে, কোনো কিছুর জন্য label লাগবে বলে নিশ্চিত না হওয়া পর্যন্ত label যোগ করবেন না Source 33সোর্স 33।

LogQL। সব LogQL query-তে একটা log stream selector থাকে Source 34সোর্স 34। ঐচ্ছিকভাবে log stream selector-এর পরে একটা log pipeline থাকতে পারে Source 34সোর্স 34। log pipeline হলো stage expression-এর একটা সেট, যা একটার পর একটা জোড়া লাগে আর বেছে নেওয়া log stream-এ প্রয়োগ হয় Source 34সোর্স 34। log stream selector ঠিক করা হয় এক বা একাধিক কমা দিয়ে আলাদা করা key-value জোড়া দিয়ে Source 34সোর্স 34। label matching operator হলো = (হুবহু সমান), != (সমান নয়), =~ (regex মেলে) আর !~ (regex মেলে না) Source 34সোর্স 34। line filter expression মিলে যাওয়া log stream-এর একত্র করা log-এর ওপর একটা distributed grep চালায় Source 34সোর্স 34। সে log লাইনের বিষয়বস্তুতে খোঁজে, আর case-sensitive expression-এর সঙ্গে না মেলা লাইন বাদ দেয় Source 34সোর্স 34। label filter expression মূল আর বের করা label ব্যবহার করে log লাইন ছেঁকে নিতে দেয় Source 34সোর্স 34। metric query log query-র ফলে একটা function প্রয়োগ করে log query-কে বাড়ায় Source 35সোর্স 35। count_over_time(log-range) দেওয়া পরিসরের মধ্যে প্রতিটা log stream-এর entry গোনে Source 35সোর্স 35।

Loki HTTP API। push endpoint ব্যবহার করলে timestamp পাঠাতে হবে string হিসেবে, সংখ্যা হিসেবে নয়, নইলে endpoint 400 error ফেরত দেবে Source 36সোর্স 36। /loki/api/v1/query_range endpoint একটা সময়ের পরিসরের ওপর query করতে ব্যবহার হয় Source 36সোর্স 36। এর limit parameter হলো ফেরত দেওয়ার entry-র সর্বোচ্চ সংখ্যা, আর তার default 100 Source 36সোর্স 36। এর start parameter-এর default এক ঘণ্টা আগে Source 36সোর্স 36। /loki/api/v1/query আর /loki/api/v1/query_range-এর মতো query endpoint query চালানোর একটা পরিসংখ্যান-সেট ফেরত দেয় Source 36সোর্স 36। /ready endpoint HTTP 200 ফেরত দেয়, যখন Loki instance traffic নিতে প্রস্তুত Source 36সোর্স 36। /loki/api/v1/labels endpoint একটা নির্দিষ্ট সময়ের পরিসরে জানা label-এর তালিকা আনে Source 36সোর্স 36।

Trace আর context propagation। context propagation থাকলে signal (trace, metric আর log) একে অপরের সঙ্গে মেলানো যায়, সেগুলো যেখানেই তৈরি হোক Source 3সোর্স 3। Propagation হলো সেই প্রক্রিয়া, যা context-কে service আর process-এর মধ্যে নিয়ে যায় Source 3সোর্স 3। Propagation সাধারণত instrumentation library সামলায় আর ব্যবহারকারীর কাছে স্বচ্ছ থাকে Source 3সোর্স 3। OpenTelemetry দূরের service-এ context পাঠাতে W3C Trace Context HTTP header ব্যবহার করে একটা text-ভিত্তিক পদ্ধতি দেয় Source 4সোর্স 4। traceparent HTTP header field একটা tracing system-এ আসা অনুরোধ চিহ্নিত করে Source 6সোর্স 6। এতে চারটা field আছে: version, trace-id, parent-id আর trace-flags Source 6সোর্স 6। trace-id একটা ১৬ byte-এর array হিসেবে উপস্থাপিত হয়, আর সব byte শূন্য হলে মানটা অবৈধ ধরা হয় Source 6সোর্স 6। parent-id একটা ৮ byte-এর array হিসেবে উপস্থাপিত হয়, আর সব byte শূন্য হলে মানটা অবৈধ ধরা হয় Source 6সোর্স 6। flags-এর সবচেয়ে কম গুরুত্বের bit সেট থাকলে বোঝায়, caller trace data রেকর্ড করে থাকতে পারে Source 6সোর্স 6। এটা একটা bit field, তাই hex মান decode করে ফলের সংখ্যা দেখে flags বোঝা যায় না Source 6সোর্স 6। Python-এ পাঠানো service বর্তমান context inject করে Source 4সোর্স 4। গ্রহণকারী service context extract করে, যেমন parse করা HTTP header থেকে, আর তারপর সেটাকে বর্তমান trace context হিসেবে বসায় Source 4সোর্স 4। page বলে context propagate করতে instrumentation library ব্যবহার করতে Source 4সোর্স 4। ConsoleSpanExporter opentelemetry-sdk package-এর সঙ্গেই আসে Source 5সোর্স 5।

monitoring-কে নিজেই test করা। আপনার rule test করতে আপনি promtool ব্যবহার করতে পারেন Source 16সোর্স 16। promtool check config command দেখে config file বৈধ কি না Source 26সোর্স 26। promtool check rules command দেখে rule file বৈধ কি না Source 26সোর্স 26। promtool test rules command rule-এর unit test চালায় Source 26সোর্স 26। একটা test file-এ test করার জন্য বিবেচনা করা rule file-এর একটা তালিকা থাকে Source 16সোর্স 16। input series একটা expanding notation ব্যবহার করে Source 16সোর্স 16। তাতে _ scrape থেকে একটা অনুপস্থিত sample বোঝায় Source 16সোর্স 16। একটা alert test একটা alertname-এর সব firing alert-এর সংযোগ একটাই alert test case-এর নিচে তালিকাভুক্ত করে Source 16সোর্স 16। একটা alerting rule firing নয়, তা test করতে আপনি field-গুলো লিখতে পারেন আর exp_alerts ফাঁকা রাখতে পারেন Source 16সোর্স 16। একটা PromQL expression-এর test-এ expression, মূল্যায়নের সময় আর প্রত্যাশিত sample-এর নাম থাকে Source 16সোর্স 16।

Try it

The tutorial ran steps 1 to 8 on 2026-11-19 at 17:11 (+06) on Linux 7.0.0-43-generic, with Prometheus 3.16.0, Alertmanager 0.35.0, Loki 3.7.10, OpenTelemetry SDK 1.45.2, Python 3.14.4 for the app and the helper scripts, Python 3.14.9 for the SDK, and bash 5.3.9. The output on this page is from the tutorial's run. Each step ran in its own shell, in a copy of the practice folder, with a new, empty HOME. The page shows the folder of the run as /work, and the virtual environment of the SDK as /venv.

The app, Prometheus, Alertmanager, and the HTTP port of Loki listen on 127.0.0.1. The gRPC port of Loki kept its default address. The tutorial found no setting that keeps that port on 127.0.0.1 in this one-process setup. It tried two. With grpc_listen_address: 127.0.0.1, the first Loki query got no answer. With instance_interface_names: [lo], Loki stopped at its start with no useable address found for interfaces [lo]. In the tutorial's run the servers listened on *:19096 (Loki, gRPC), 127.0.0.1:13100 (Loki), 127.0.0.1:19090 (Prometheus), and 127.0.0.1:19093 (Alertmanager). Run step 7 on a machine and a network that you trust, because the gRPC port of Loki accepts connections on all addresses. No step needs a cloud account, a container, or a remote host.

The choices that no source gives are the tutorial's own: the app, the file names, the names inside the files, the ports, the data folders, the short intervals (5s, 15s, and 10s), the traffic of the steps, the wrong test of step 3, the severity label and the receiver names, and the helper functions of step 6 and step 7. The tutorial did not run Grafana, the OpenTelemetry Collector, Grafana Alloy or Promtail, a tracing backend such as Jaeger, notifications to a real receiver, inhibition rules, high availability, or remote storage. Those parts are described from the docs only.

Install the tools. The Prometheus docs say that they provide precompiled binaries for most official Prometheus components Source 30সোর্স 30. They also say that running Prometheus on Docker is as simple as docker run -p 9090:9090 prom/prometheus Source 30সোর্স 30. The Loki docs say that you can install Loki and Alloy with Docker or Docker Compose if you are evaluating, testing, or developing Loki Source 39সোর্স 39. The tutorial followed neither Docker page. It installed the release binaries for one user, so that no container and no image touched the Docker host of the machine. That is the tutorial's own choice.

On 2026-11-19 at 16:48, the tutorial's install script downloaded the release archives of Prometheus 3.16.0 and Loki 3.7.10 from the GitHub release pages of the two projects. At 16:56 it did the same for Alertmanager 0.35.0. For each archive, it compared the SHA-256 with the value in the checksum file of the same release, and the two values were the same. The archives start with 68727009 (Prometheus), 200e74f7 (Loki), and 6c7752a9 (Alertmanager). The check has limits. The checksum file comes from the same host as the archive, and the release pages listed no signature file next to it that day. So the check finds a damaged or a swapped archive, and it does not prove who built it. The scripts put prometheus, promtool, alertmanager, amtool, and loki into ~/.local/bin.

For OpenTelemetry, the tutorial made a virtual environment with Python 3.14.9 and installed opentelemetry-sdk 1.45.2 in it at 16:56. It downloaded the wheel first, and compared its SHA-256, which starts with ff974ea7, with the value that the PyPI JSON API lists for that file. The two values were the same. The dependencies were installed by pip from PyPI over HTTPS, without hash pinning. All of this is the tutorial's own choice.

1. Start a small web app, and read its metrics. The app is the tutorial's own, written for this lesson. It uses only the standard library. It counts its requests by path and status code, times each request, and writes one log line per request. The path / answers 200, /slow answers 200 after 0.3 s, /fail answers 500, and any other path answers 404. Save this as app.py:

"""A tiny web app for the practice run: it counts and times its own requests and shows them at /metrics.

  python3 app.py PORT LOGFILE

The routes are /, /slow (sleeps 0.3 s), /fail (answers 500), /metrics, and anything else (404). It uses only the
standard library. The metrics are written in the text format of Prometheus, and each request is also logged as one
line of key=value pairs.
"""
import http.server
import sys
import threading
import time
from collections import Counter

BUCKETS = (0.05, 0.1, 0.25, 0.5, 1.0)
LOCK = threading.Lock()
REQUESTS = Counter()  # (path, code) -> number of requests
BUCKET_COUNTS = [0] * (len(BUCKETS) + 1)  # observations per bucket (the last one is above 1.0)
STATE = {"sum": 0.0, "count": 0, "in_flight": 0}
PORT, LOGFILE = int(sys.argv[1]), sys.argv[2]
LOG = open(LOGFILE, "a", buffering=1, encoding="utf-8")


def render():
    lines = ["# HELP app_requests_total Requests handled, by path and status code.", "# TYPE app_requests_total counter"]
    for (path, code), n in sorted(REQUESTS.items()):
        lines.append(f'app_requests_total{{path="{path}",code="{code}"}} {n}')
    lines += ["# HELP app_in_flight_requests Requests that are being handled now.", "# TYPE app_in_flight_requests gauge",
              f"app_in_flight_requests {STATE['in_flight']}",
              "# HELP app_request_duration_seconds Time to handle a request.", "# TYPE app_request_duration_seconds histogram"]
    cumulative = 0
    for bound, n in zip(BUCKETS, BUCKET_COUNTS):
        cumulative += n
        lines.append(f'app_request_duration_seconds_bucket{{le="{bound}"}} {cumulative}')
    lines += [f'app_request_duration_seconds_bucket{{le="+Inf"}} {STATE["count"]}',
              f'app_request_duration_seconds_sum {STATE["sum"]:.6f}', f'app_request_duration_seconds_count {STATE["count"]}']
    return "\n".join(lines) + "\n"


class Handler(http.server.BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def reply(self, code, body, ctype="text/plain; charset=utf-8"):
        data = body.encode()
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/metrics":
            with LOCK:
                self.reply(200, render(), "text/plain; version=0.0.4; charset=utf-8")
            return
        started = time.time()
        with LOCK:
            STATE["in_flight"] += 1
        if self.path == "/slow":
            time.sleep(0.3)
        code = {"/": 200, "/slow": 200, "/fail": 500}.get(self.path, 404)
        self.reply(code, f"{code}\n")
        took = time.time() - started
        with LOCK:
            STATE["in_flight"] -= 1
            REQUESTS[(self.path if code != 404 else "other", code)] += 1
            STATE["sum"] += took
            STATE["count"] += 1
            BUCKET_COUNTS[next((i for i, b in enumerate(BUCKETS) if took <= b), len(BUCKETS))] += 1
        level = "error" if code >= 500 else "info"
        now = time.time()
        stamp = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(now)) + f".{int(now % 1 * 1000):03d}Z"
        LOG.write(f"ts={stamp} level={level} path={self.path} code={code} duration_ms={took * 1000:.0f}\n")


http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

Run:

python3 app.py 18000 app.log > app.out 2>&1 &
echo $! > app.pid
sleep 1
for path in / / / / / /slow /fail /fail /nope; do curl -s -o /dev/null -w "$path -> %{http_code}\n" "localhost:18000$path"; done
curl -s localhost:18000/metrics

Output of the tutorial's run:

/ -> 200
/ -> 200
/ -> 200
/ -> 200
/ -> 200
/slow -> 200
/fail -> 500
/fail -> 500
/nope -> 404
# HELP app_requests_total Requests handled, by path and status code.
# TYPE app_requests_total counter
app_requests_total{path="/",code="200"} 5
app_requests_total{path="/fail",code="500"} 2
app_requests_total{path="/slow",code="200"} 1
app_requests_total{path="other",code="404"} 1
# HELP app_in_flight_requests Requests that are being handled now.
# TYPE app_in_flight_requests gauge
app_in_flight_requests 0
# HELP app_request_duration_seconds Time to handle a request.
# TYPE app_request_duration_seconds histogram
app_request_duration_seconds_bucket{le="0.05"} 8
app_request_duration_seconds_bucket{le="0.1"} 8
app_request_duration_seconds_bucket{le="0.25"} 8
app_request_duration_seconds_bucket{le="0.5"} 9
app_request_duration_seconds_bucket{le="1.0"} 9
app_request_duration_seconds_bucket{le="+Inf"} 9
app_request_duration_seconds_sum 0.306769
app_request_duration_seconds_count 9
  • The /metrics page is plain text. The lines that start with # HELP and # TYPE are comments, which the format uses for help text and for the type of a metric Source 17সোর্স 17.
  • app_requests_total is a counter with the labels path and code. Its name ends in _total, which is the convention for counters Source 12সোর্স 12. The nine requests of the run gave the values 5, 1, 2, and 1. The tutorial's app counts a path that does not exist under the label other. That is the tutorial's own choice.
  • app_in_flight_requests is a gauge, a value that can go up and down Source 10সোর্স 10. Its value was 0 when the page was read.
  • app_request_duration_seconds is a histogram. Its buckets are cumulative counters Source 10সোর্স 10. Eight requests took 0.05 s or less, and all nine took 0.5 s or less. The sum was 0.306769 s, which is mostly the 0.3 s of /slow. The sum is different on every run.

2. Write the Prometheus files, and check them without a server. Save the scrape configuration as prometheus.yml:

global:
  scrape_interval: 5s
  evaluation_interval: 5s

rule_files:
  - rules.yml

alerting:
  alertmanagers:
    - static_configs:
        - targets: ["127.0.0.1:19093"]

scrape_configs:
  - job_name: app
    static_configs:
      - targets: ["127.0.0.1:18000"]

Save the rules as rules.yml:

groups:
  - name: app
    interval: 5s
    rules:
      - record: job:app_requests:rate1m
        expr: sum by (job) (rate(app_requests_total[1m]))
      - alert: AppHighErrorRatio
        expr: sum(rate(app_requests_total{code=~"5.."}[1m])) / sum(rate(app_requests_total[1m])) > 0.2
        for: 15s
        labels:
          severity: page
        annotations:
          summary: More than 20% of the requests fail.
      - alert: AppDown
        expr: up{job="app"} == 0
        for: 10s
        labels:
          severity: page
        annotations:
          summary: The app does not answer its scrapes.

Run:

promtool check config prometheus.yml
promtool check rules rules.yml

Output of the tutorial's run:

Checking prometheus.yml
  SUCCESS: 1 rule files found
 SUCCESS: prometheus.yml is valid prometheus config file syntax

Checking rules.yml
  SUCCESS: 3 rules found

Checking rules.yml
  SUCCESS: 3 rules found
  • The configuration has one job, app, with one static target, the app of step 1. The overview says that targets are discovered via service discovery or static configuration Source 8সোর্স 8. The block alerting points to the Alertmanager of step 5. The intervals of 5 s are the tutorial's own choice.
  • The first rule is a recording rule, job:app_requests:rate1m. Its expression takes the rate() first, and then aggregates with sum by (job), as the docs say Source 13সোর্স 13.
  • The alert AppHighErrorRatio divides the rate of the requests with a status code from 500 to 599 by the rate of all requests, and compares the result with 0.2. By default, a comparison between an instant vector and a scalar drops the elements for which it is false Source 40সোর্স 40. Their behavior can be modified by providing bool after the operator, which returns 0 or 1 for the value rather than filtering Source 40সোর্স 40. The for of 15 s means that the alert is pending until the expression has been returned for that long Source 14সোর্স 14.
  • The alert AppDown fires when up{job="app"} is 0, and up is 0 if the scrape failed Source 11সোর্স 11. Both alerts carry the label severity: page and an annotation summary Source 15সোর্স 15.
  • promtool check config checks if the config files are valid or not, and promtool check rules checks the rule files Source 26সোর্স 26. The first command printed SUCCESS for the configuration, and SUCCESS: 1 rule files found. The page of promtool lists a flag --syntax-only, which ignores the validation of the files and content that the config references Source 26সোর্স 26. The tutorial did not use that flag. The second command printed SUCCESS: 3 rules found. No Prometheus server was running in this step. The page on rules says that you can quickly check whether a rule file is syntactically correct without starting a Prometheus server, with promtool check rules Source 14সোর্স 14.

3. Unit-test the rules. Save the tests as rules.test.yml:

rule_files:
  - rules.yml
evaluation_interval: 5s

tests:
  - name: failing requests raise the error-ratio alert
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
      - series: 'app_requests_total{job="app", path="/fail", code="500"}'
        values: '0+5x24'
    alert_rule_test:
      - eval_time: 10s
        alertname: AppHighErrorRatio
        exp_alerts: []
      - eval_time: 1m
        alertname: AppHighErrorRatio
        exp_alerts:
          - exp_labels:
              severity: page
            exp_annotations:
              summary: More than 20% of the requests fail.
    promql_expr_test:
      - expr: job:app_requests:rate1m
        eval_time: 1m
        exp_samples:
          - labels: 'job:app_requests:rate1m{job="app"}'
            value: 3

  - name: healthy traffic does not raise it
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
    alert_rule_test:
      - eval_time: 1m
        alertname: AppHighErrorRatio
        exp_alerts: []

  - name: a target that stops answering raises AppDown
    interval: 5s
    input_series:
      - series: 'up{job="app", instance="127.0.0.1:18000"}'
        values: '1 1 1 0x20'
    alert_rule_test:
      - eval_time: 1m
        alertname: AppDown
        exp_alerts:
          - exp_labels:
              severity: page
              job: app
              instance: 127.0.0.1:18000
            exp_annotations:
              summary: The app does not answer its scrapes.

Save a test with a wrong expectation as bad.test.yml:

rule_files:
  - rules.yml
evaluation_interval: 5s

tests:
  - name: a wrong expectation (the rate is 3, the test says 4)
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
      - series: 'app_requests_total{job="app", path="/fail", code="500"}'
        values: '0+5x24'
    promql_expr_test:
      - expr: job:app_requests:rate1m
        eval_time: 1m
        exp_samples:
          - labels: 'job:app_requests:rate1m{job="app"}'
            value: 4

Run:

promtool test rules rules.test.yml; echo "exit status: $?"
promtool test rules bad.test.yml; echo "exit status: $?"

Output of the tutorial's run:

Processing test file: rules.test.yml
  SUCCESS

exit status: 0
Processing test file: bad.test.yml
  FAILED:
    expr: "job:app_requests:rate1m", time: 1m,
        exp: {__name__="job:app_requests:rate1m", job="app"} 4E+00
        got: {__name__="job:app_requests:rate1m", job="app"} 3E+00


exit status: 1
  • The promtool test rules command runs unit tests for rules Source 26সোর্স 26. A test file lists the rule files to consider Source 16সোর্স 16.
  • The first test group feeds two counters into the rules. 0+10x24 starts at 0 and adds 10 for 24 more samples, and 0+5x24 adds 5. The docs read it as "series starts at a, then n further samples incrementing by b" Source 16সোর্স 16. With one sample every 5 s, the counters grow by 2 and 1 per second, so the sum of the rates is 3.
  • At 10 s, the test exp_alerts: [] expects that AppHighErrorRatio is not firing. At 1 m, it expects one alert, with the labels and the annotation of the rule. The group also checks that job:app_requests:rate1m is 3 at 1 m.
  • The second group has only the good counter, and expects no alert. The third group gives up the values 1 1 1 0x20, and expects AppDown at 1 m.
  • The first file printed SUCCESS and ended with the exit status 0. The second file expects 4, and the real value is 3. The output of the failure shows the expression, the time, the expected sample (exp), and the sample that the rules gave (got), and the exit status was 1. The output of the failure and the exit statuses are from the tutorial's run.

4. Write the Alertmanager configuration, and test the routing without a server. Save it as alertmanager.yml:

route:
  receiver: team-default
  group_by: [alertname]
  group_wait: 5s
  group_interval: 10s
  repeat_interval: 1h
  routes:
    - matchers:
        - severity="page"
      receiver: team-oncall

receivers:
  - name: team-default
  - name: team-oncall

Run:

amtool check-config alertmanager.yml
amtool config routes show --config.file=alertmanager.yml
amtool config routes test --config.file=alertmanager.yml severity=page alertname=AppDown
amtool config routes test --config.file=alertmanager.yml severity=ticket alertname=AppHighErrorRatio

Output of the tutorial's run:

Checking 'alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 0 inhibit rules
 - 2 receivers
 - 0 templates

Routing tree:
.
└── default-route  receiver: team-default
    └── {severity="page"}  receiver: team-oncall

team-oncall
team-default
  • The root route sends alerts to the receiver team-default and groups them by alertname. One child route sends the alerts with severity="page" to team-oncall. The two receivers in the file have no integration settings. The values 5s, 10s, and 1h are the tutorial's own choice. The docs describe group_wait as how long to wait before sending the first notification for a new group Source 24সোর্স 24, and repeat_interval as how long to wait before repeating the last notification Source 24সোর্স 24.
  • Every alert enters the routing tree at the top-level route and then traverses the child nodes Source 24সোর্স 24.
  • amtool check-config printed SUCCESS, and it counted the route, 0 inhibit rules, 2 receivers, and 0 templates. No Alertmanager server was running yet, because step 5 starts it. The configuration page shows amtool check-config for the check of UTF-8 strict mode Source 24সোর্স 24. It says that you do not need a running Alertmanager server for that check Source 24সোর্স 24.
  • amtool config routes show printed the tree of the routes. amtool config routes test printed team-oncall for an alert with severity=page, and team-default for an alert with severity=ticket. The README of Alertmanager says that amtool can visualize the routes of a configuration as a text tree Source 25সোর্স 25. It says that you can also use it to test the routing, by passing it the label set of an alert Source 25সোর্স 25. The README writes the two commands as amtool config routes Source 25সোর্স 25 and amtool config routes test Source 25সোর্স 25. The tutorial ran the first as config routes show, and the README does not write it that way.

5. Start the servers, and ask Prometheus questions. Run:

alertmanager --config.file=alertmanager.yml --storage.path=am-data --web.listen-address=127.0.0.1:19093 --cluster.listen-address= > am.out 2>&1 &
echo $! > am.pid
prometheus --config.file=prometheus.yml --storage.tsdb.path=prom-data --web.listen-address=127.0.0.1:19090 > prom.out 2>&1 &
echo $! > prom.pid
until curl -sf localhost:19090/-/ready; do sleep 1; done
sleep 12
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=up'; echo
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=sum by (code) (app_requests_total)'; echo
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=histogram_quantile(0.9, sum by (le) (app_request_duration_seconds_bucket))'; echo

Output of the tutorial's run:

Prometheus Server is Ready.
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","instance":"127.0.0.1:18000","job":"app"},"value":[1795086690.402,"1"]}]}}
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"code":"200"},"value":[1795086690.416,"6"]},{"metric":{"code":"500"},"value":[1795086690.416,"2"]},{"metric":{"code":"404"},"value":[1795086690.416,"1"]}]}}
{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1795086690.431,"0.2749999999999999"]}]}}
  • The flag --config.file is the Prometheus configuration file path Source 29সোর্স 29. The flag --storage.tsdb.path is the base path for metrics storage Source 29সোর্স 29. The flag --web.listen-address is the address to listen on for UI, API, and telemetry Source 29সোর্স 29. The data folders, and the ports 19090 and 19093, are the tutorial's own choice.
  • Setting --cluster.listen-address= prevents Alertmanager from listening to incoming peer requests Source 25সোর্স 25. The tutorial set it. The sockets of the run show no gossip port.
  • /-/ready printed Prometheus Server is Ready. That endpoint returns 200 when Prometheus is ready to serve traffic Source 28সোর্স 28. The until loop of the tutorial waits for it.
  • The API response format is JSON Source 27সোর্স 27. The endpoint /api/v1/query evaluates an instant query at a single point in time Source 27সোর্স 27.
  • The query up returned one series, with the value "1". That means the instance was healthy, that is, reachable Source 11সোর্স 11.
  • The query sum by (code) (app_requests_total) returned 6 for the code 200, 2 for 500, and 1 for 404. They are the totals of step 1: five requests to / and one to /slow made six 200s.
  • The query histogram_quantile(0.9, sum by (le) (app_request_duration_seconds_bucket)) returned 0.2749999999999999. Eight of the nine requests were in the buckets up to 0.25 s. The docs say that the φ-quantile is the observation value that ranks at number φ*N among the N observations Source 20সোর্স 20. For φ = 0.9 and N = 9, the rank is 8.1, so the tutorial's own arithmetic puts the answer in the bucket from 0.25 to 0.5, which holds the ninth request. The function interpolates the quantile value within the bucket that it falls into Source 13সোর্স 13. For classic histograms, it assumes a uniform distribution of observations within the bucket Source 13সোর্স 13. That gives 0.25 plus 0.1 times 0.25, which is 0.275.
  • The tutorial left out rate() in that query, so the answer covers all nine requests since the app started. The docs use the rate() function to specify the time window Source 13সোর্স 13. That is the tutorial's own choice, so that the number can be repeated.

6. Make the alerts fire, and look at them in Alertmanager. The step defines helper functions that the tutorial wrote. alerts prints the name and the state of each alert from the endpoint /api/v1/alerts. wait_for loops until a given line shows. In the background, a loop sends two failing requests for every good one. Run:

alerts() { curl -s localhost:19090/api/v1/alerts | python3 -c 'import json, sys; [print(a["labels"]["alertname"], a["state"]) for a in json.load(sys.stdin)["data"]["alerts"]]'; }
wait_for() { until alerts | grep -q "$1"; do sleep 1; done; echo "--- Prometheus reports: $1"; alerts; }
AM="amtool --alertmanager.url=http://127.0.0.1:19093"

# traffic with two failing requests for every good one, in the background
( while true; do curl -s -o /dev/null localhost:18000/; curl -s -o /dev/null localhost:18000/fail; curl -s -o /dev/null localhost:18000/fail; sleep 1; done ) &
echo $! > traffic.pid
wait_for "AppHighErrorRatio pending"
wait_for "AppHighErrorRatio firing"
kill "$(cat traffic.pid)"
until $AM alert query | grep -q AppHighErrorRatio; do sleep 1; done
echo "--- Alertmanager received it:"; $AM alert query
$AM silence add alertname=AppHighErrorRatio --author=tutorial --comment="practice run" --duration=10m
echo "--- after the silence:"; $AM alert query; echo "(the line above ends the list of active alerts)"; $AM alert query --silenced

# stop the app: the scrape fails and up becomes 0
kill "$(cat app.pid)"
wait_for "AppDown pending"
wait_for "AppDown firing"
until $AM alert query | grep -q AppDown; do sleep 1; done
echo "--- Alertmanager received it:"; $AM alert query

Output of the tutorial's run:

--- Prometheus reports: AppHighErrorRatio pending
AppHighErrorRatio pending
--- Prometheus reports: AppHighErrorRatio firing
AppHighErrorRatio firing
--- Alertmanager received it:
Alertname          Starts At                Summary                              State   
AppHighErrorRatio  2026-11-19 11:11:51 UTC  More than 20% of the requests fail.  active  
d009a065-d5f7-4960-9a46-5f79f358f22e
--- after the silence:
Alertname  Starts At  Summary  State  
(the line above ends the list of active alerts)
Alertname          Starts At                Summary                              State       
AppHighErrorRatio  2026-11-19 11:11:51 UTC  More than 20% of the requests fail.  suppressed  
--- Prometheus reports: AppDown pending
AppHighErrorRatio firing
AppDown pending
--- Prometheus reports: AppDown firing
AppHighErrorRatio firing
AppDown firing
--- Alertmanager received it:
Alertname  Starts At                Summary                               State   
AppDown    2026-11-19 11:12:11 UTC  The app does not answer its scrapes.  active  
  • The /alerts endpoint returns a list of all active alerts Source 27সোর্স 27.
  • AppHighErrorRatio was reported as pending, and later as firing. An alert is pending until it has been returned for the for time Source 14সোর্স 14. While the app answered 500, this was the only alert in the list.
  • amtool alert query printed the alert with the state active. The Starts At column is in UTC. The tutorial's time zone was +06, so the time of the alert is six hours behind the clock of the machine.
  • The README shows amtool silence add alertname=Test_Alert Source 25সোর্স 25. The Alertmanager page says that silences are configured in the web interface Source 23সোর্স 23. The tutorial used amtool instead, and it printed the ID of the new silence. After that, amtool alert query listed no active alert, and with --silenced it listed the alert with the state suppressed. No page that the tutorial read describes the flag --silenced or the state suppressed.
  • After the app was stopped, Prometheus reported AppDown as pending, and later as firing. Its up was 0, because the scrape failed Source 11সোর্স 11. AppHighErrorRatio was still firing at that time, and the tutorial did not wait to see when it ends.
  • Alertmanager listed AppDown as active. The other alert was silenced, so it was not in the list.

7. Start Loki, send the log lines of the app to it, and query them. The Loki configuration comes from the docs. The page lists a complete configuration to deploy Loki backed by the filesystem Source 37সোর্স 37. The tutorial changed the ports, and the folder, which is loki-data here and /tmp/loki on the page Source 37সোর্স 37. It also set the HTTP listen address, and it added analytics with reporting_enabled: false. The configuration reference describes that setting as "Enable anonymous usage reporting" Source 38সোর্স 38. Save it as loki.yml:

auth_enabled: false

server:
  http_listen_address: 127.0.0.1
  http_listen_port: 13100
  grpc_listen_port: 19096

common:
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory
  replication_factor: 1
  path_prefix: loki-data

schema_config:
  configs:
    - from: 2020-05-15
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

storage_config:
  filesystem:
    directory: loki-data/chunks

analytics:
  reporting_enabled: false

The sender push.py is the tutorial's own. It reads the lines of app.log, and sends them as one stream with the label job="app":

"""Send the lines of an app log to Loki, as one stream with the label job="app".

  python3 push.py app.log http://127.0.0.1:13100
Each line starts with ts=<UTC time with milliseconds>. That time becomes the timestamp of the entry in Loki.
"""
import datetime
import json
import re
import sys
import urllib.request

path, base = sys.argv[1], sys.argv[2]
values = []
for line in open(path, encoding="utf-8").read().splitlines():
    stamp = re.match(r"ts=(\S+)", line).group(1)
    when = datetime.datetime.fromisoformat(stamp)
    values.append([str(int(when.timestamp() * 1000) * 1_000_000), line])
body = json.dumps({"streams": [{"stream": {"job": "app"}, "values": values}]}).encode()
request = urllib.request.Request(base + "/loki/api/v1/push", data=body, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request) as response:
    print(f"pushed {len(values)} lines, HTTP status {response.status}")

Run:

loki -config.file=loki.yml > loki.out 2>&1 &
echo $! > loki.pid
until [ "$(curl -s -o /dev/null -w '%{http_code}' localhost:13100/ready)" = 200 ]; do sleep 2; done
curl -s localhost:13100/ready
python3 push.py app.log http://127.0.0.1:13100
# a helper that prints the result and leaves out the "stats" field of the response
lq() { curl -s --get "localhost:13100/loki/api/v1/$1" --data-urlencode "query=$2" "${@:3}" | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["status"], d["data"]["resultType"]); print(json.dumps(d["data"]["result"]))'; }
curl -s localhost:13100/loki/api/v1/labels; echo
lq query_range '{job="app"} |= "code=500"' --data-urlencode limit=2
lq query 'sum by (path) (count_over_time({job="app"} | logfmt | code >= 500 [1h]))'

Output of the tutorial's run:

ready
pushed 69 lines, HTTP status 204
{"status":"success","data":["job","service_name"]}

success streams
[{"stream": {"detected_level": "error", "job": "app", "service_name": "app"}, "values": [["1795086711780000000", "ts=2026-11-19T11:11:51.780Z level=error path=/fail code=500 duration_ms=1"], ["1795086711754000000", "ts=2026-11-19T11:11:51.754Z level=error path=/fail code=500 duration_ms=0"]]}]
success vector
[{"metric": {"path": "/fail"}, "value": [1795086751.347, "42"]}]
  • /ready printed ready. That endpoint returns HTTP 200 when the Loki instance is ready to accept traffic Source 36সোর্স 36. The loop of the tutorial waits for the status 200.
  • push.py sent 69 lines, and the endpoint answered with the status 204. The timestamp of each entry is a string, as the API needs Source 36সোর্স 36.
  • The labels endpoint returned job and service_name. The tutorial sent only job. Loki added service_name itself, with the value app, which is the value of job. If no service_name is on the stream, Loki looks for the first non-empty value from a list of labels, in order Source 32সোর্স 32.
  • The stream of the first result also has the label detected_level, with the value error. The configuration reference says that Loki can discover and add log levels during ingestion, if not present already Source 38সোর্স 38. The tutorial did not set it, and no page that the tutorial read names the key detected_level.
  • The log query {job="app"} |= "code=500" selects the stream, and keeps the lines with code=500. A line filter expression does a distributed grep over the log streams that match, and discards the lines that do not match Source 34সোর্স 34. The limit=2 kept two entries. The parameter limit is the max number of entries to return, and it defaults to 100 Source 36সোর্স 36.
  • The metric query sum by (path) (count_over_time({job="app"} | logfmt | code >= 500 [1h])) returned one series, path="/fail", with the value 42. The function count_over_time counts the entries for each log stream within the given range Source 35সোর্স 35. The logfmt stage parses each log line to extract more labels, and the next stage filters with them Source 34সোর্স 34. The log file had 42 lines for /fail, so the two numbers agree. The number differs on every run, because it depends on how many requests the loop of step 6 sent.
  • The helper lq leaves out the field stats of the response. Query endpoints return a set of statistics about the query execution Source 36সোর্স 36.

8. Pass a trace context from one service to another. The script has two services in one process, service-a and service-b. The dictionary headers stands in for the HTTP request between them, so no network is used. The script uses the ConsoleSpanExporter of the SDK, which is included in the opentelemetry-sdk package Source 5সোর্স 5. It passes the context by hand, as the Python docs show Source 4সোর্স 4. The same page says to use instrumentation libraries to propagate context Source 4সোর্স 4. The function one_line and the five checks are the tutorial's own. Save the script as otel_demo.py:

"""Trace context propagation with the OpenTelemetry Python SDK: two "services" in one process.

The dictionary `headers` stands in for the HTTP request between them. Each span is printed on one line when it ends.
"""
import json
import re

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

SPANS = []


def one_line(span):
    d = json.loads(span.to_json())
    row = {"name": d["name"], "trace_id": d["context"]["trace_id"], "span_id": d["context"]["span_id"], "parent_id": d["parent_id"]}
    SPANS.append(row)
    return json.dumps(row) + "\n"


provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("practice")
propagator = TraceContextTextMapPropagator()


def service_b(headers):
    context = propagator.extract(carrier=headers)
    with tracer.start_as_current_span("service-b handles the request", context=context):
        pass


print("case 1: service A sends the traceparent header")
with tracer.start_as_current_span("service-a calls service-b"):
    headers = {}
    propagator.inject(headers)
    print("traceparent:", headers["traceparent"])
    service_b(headers)

print("case 2: the header is lost on the way")
with tracer.start_as_current_span("service-a calls service-b, no header"):
    service_b({})

b1, a1, b2, a2 = SPANS  # a span is printed when it ends, so each service-b span comes before its service-a span
print("check 1: header has the form 00-<32 hex>-<16 hex>-<2 hex>:", bool(re.fullmatch(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", headers["traceparent"])))
print("check 2: case 1, both spans share one trace id:", a1["trace_id"] == b1["trace_id"])
print("check 3: case 1, the parent of the service-b span is the service-a span:", b1["parent_id"] == a1["span_id"])
print("check 4: case 2, the trace ids differ:", a2["trace_id"] != b2["trace_id"])
print("check 5: case 2, the service-b span has no parent:", b2["parent_id"] is None)

Run:

venv/bin/python otel_demo.py

Output of the tutorial's run:

case 1: service A sends the traceparent header
traceparent: 00-0476e04404089b682e7a22e120886d1e-d4f79e01e18511ac-03
{"name": "service-b handles the request", "trace_id": "0x0476e04404089b682e7a22e120886d1e", "span_id": "0x60a1a9c5df67ed51", "parent_id": "0xd4f79e01e18511ac"}
{"name": "service-a calls service-b", "trace_id": "0x0476e04404089b682e7a22e120886d1e", "span_id": "0xd4f79e01e18511ac", "parent_id": null}
case 2: the header is lost on the way
{"name": "service-b handles the request", "trace_id": "0x20c17ac1fac019492a3ea81ed585d55e", "span_id": "0xf955daacc6d0807c", "parent_id": null}
{"name": "service-a calls service-b, no header", "trace_id": "0x180f73c286f70edb200fa915c2cd2174", "span_id": "0x95f1c3f4063851ef", "parent_id": null}
check 1: header has the form 00-<32 hex>-<16 hex>-<2 hex>: True
check 2: case 1, both spans share one trace id: True
check 3: case 1, the parent of the service-b span is the service-a span: True
check 4: case 2, the trace ids differ: True
check 5: case 2, the service-b span has no parent: True
  • In case 1, service A put the context into headers. The header has the four fields Source 6সোর্স 6. Its last field was 03. The right-most bit of the flags, when set, denotes that the caller may have recorded trace data Source 6সোর্স 6. The page also says that the flags are a bit field, and that you cannot read them as a number Source 6সোর্স 6. So 03 means that the right-most bit is set, and that another bit is set too. No page that the tutorial read names that other bit.
  • The two spans of case 1 have the same trace_id. The parent_id of the span of service B is the span_id of the span of service A. The span of service A has a trace_id but no parent_id, and that is how you know that it is a root span Source 41সোর্স 41.
  • In case 2, the header was lost, and service B started a new trace: its trace_id is different, and it has no parent. The W3C page says that, when no traceparent header is received, the vendor creates a new trace-id and parent-id that represents the current request Source 6সোর্স 6. The service-A span of case 2 has a third trace id, because it is a new root span too.
  • The five checks of the script printed True. Case 2 shows what broken propagation looks like: two traces with different ids, where one trace was expected.

সহজ English

The tutorial ran steps 1 to 8 on 2026-11-19 at 17:11 (+06) on Linux 7.0.0-43-generic, with Prometheus 3.16.0, Alertmanager 0.35.0, Loki 3.7.10, OpenTelemetry SDK 1.45.2, Python 3.14.4 for the app and the helper scripts, Python 3.14.9 for the SDK, and bash 5.3.9. The output on this page is from the tutorial's run. Each step ran in its own shell, in a copy of the practice folder, with a new, empty HOME. The page shows the folder of the run as /work, and the virtual environment of the SDK as /venv.

The app, Prometheus, Alertmanager, and the HTTP port of Loki listen on 127.0.0.1. The gRPC port of Loki kept its default address. The tutorial found no setting that keeps that port on 127.0.0.1 in this one-process setup. It tried two. With grpc_listen_address: 127.0.0.1, the first Loki query got no answer. With instance_interface_names: [lo], Loki stopped at its start with no useable address found for interfaces [lo]. In the tutorial's run the servers listened on *:19096 (Loki, gRPC), 127.0.0.1:13100 (Loki), 127.0.0.1:19090 (Prometheus), and 127.0.0.1:19093 (Alertmanager). Run step 7 on a machine and a network that you trust, because the gRPC port of Loki accepts connections on all addresses. No step needs a cloud account, a container, or a remote host.

The choices that no source gives are the tutorial's own: the app, the file names, the names inside the files, the ports, the data folders, the short intervals (5s, 15s, and 10s), the traffic of the steps, the wrong test of step 3, the severity label and the receiver names, and the helper functions of step 6 and step 7. The tutorial did not run Grafana, the OpenTelemetry Collector, Grafana Alloy or Promtail, a tracing backend such as Jaeger, notifications to a real receiver, inhibition rules, high availability, or remote storage. Those parts are described from the docs only.

Install the tools. The Prometheus docs say that they provide precompiled binaries for most official Prometheus components Source 30সোর্স 30. They also say that running Prometheus on Docker is as simple as docker run -p 9090:9090 prom/prometheus Source 30সোর্স 30. The Loki docs say that you can install Loki and Alloy with Docker or Docker Compose if you are evaluating, testing, or developing Loki Source 39সোর্স 39. The tutorial followed neither Docker page. It installed the release binaries for one user, so that no container and no image touched the Docker host of the machine. That is the tutorial's own choice.

On 2026-11-19 at 16:48, the tutorial's install script downloaded the release archives of Prometheus 3.16.0 and Loki 3.7.10 from the GitHub release pages of the two projects. At 16:56 it did the same for Alertmanager 0.35.0. For each archive, it compared the SHA-256 with the value in the checksum file of the same release, and the two values were the same. The archives start with 68727009 (Prometheus), 200e74f7 (Loki), and 6c7752a9 (Alertmanager). The check has limits. The checksum file comes from the same host as the archive, and the release pages listed no signature file next to it that day. So the check finds a damaged or a swapped archive, and it does not prove who built it. The scripts put prometheus, promtool, alertmanager, amtool, and loki into ~/.local/bin.

For OpenTelemetry, the tutorial made a virtual environment with Python 3.14.9 and installed opentelemetry-sdk 1.45.2 in it at 16:56. It downloaded the wheel first, and compared its SHA-256, which starts with ff974ea7, with the value that the PyPI JSON API lists for that file. The two values were the same. The dependencies were installed by pip from PyPI over HTTPS, without hash pinning. All of this is the tutorial's own choice.

1. Start a small web app, and read its metrics. The app is the tutorial's own, written for this lesson. It uses only the standard library. It counts its requests by path and status code, times each request, and writes one log line per request. The path / answers 200, /slow answers 200 after 0.3 s, /fail answers 500, and any other path answers 404. Save this as app.py:

"""A tiny web app for the practice run: it counts and times its own requests and shows them at /metrics.

  python3 app.py PORT LOGFILE

The routes are /, /slow (sleeps 0.3 s), /fail (answers 500), /metrics, and anything else (404). It uses only the
standard library. The metrics are written in the text format of Prometheus, and each request is also logged as one
line of key=value pairs.
"""
import http.server
import sys
import threading
import time
from collections import Counter

BUCKETS = (0.05, 0.1, 0.25, 0.5, 1.0)
LOCK = threading.Lock()
REQUESTS = Counter()  # (path, code) -> number of requests
BUCKET_COUNTS = [0] * (len(BUCKETS) + 1)  # observations per bucket (the last one is above 1.0)
STATE = {"sum": 0.0, "count": 0, "in_flight": 0}
PORT, LOGFILE = int(sys.argv[1]), sys.argv[2]
LOG = open(LOGFILE, "a", buffering=1, encoding="utf-8")


def render():
    lines = ["# HELP app_requests_total Requests handled, by path and status code.", "# TYPE app_requests_total counter"]
    for (path, code), n in sorted(REQUESTS.items()):
        lines.append(f'app_requests_total{{path="{path}",code="{code}"}} {n}')
    lines += ["# HELP app_in_flight_requests Requests that are being handled now.", "# TYPE app_in_flight_requests gauge",
              f"app_in_flight_requests {STATE['in_flight']}",
              "# HELP app_request_duration_seconds Time to handle a request.", "# TYPE app_request_duration_seconds histogram"]
    cumulative = 0
    for bound, n in zip(BUCKETS, BUCKET_COUNTS):
        cumulative += n
        lines.append(f'app_request_duration_seconds_bucket{{le="{bound}"}} {cumulative}')
    lines += [f'app_request_duration_seconds_bucket{{le="+Inf"}} {STATE["count"]}',
              f'app_request_duration_seconds_sum {STATE["sum"]:.6f}', f'app_request_duration_seconds_count {STATE["count"]}']
    return "\n".join(lines) + "\n"


class Handler(http.server.BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def reply(self, code, body, ctype="text/plain; charset=utf-8"):
        data = body.encode()
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/metrics":
            with LOCK:
                self.reply(200, render(), "text/plain; version=0.0.4; charset=utf-8")
            return
        started = time.time()
        with LOCK:
            STATE["in_flight"] += 1
        if self.path == "/slow":
            time.sleep(0.3)
        code = {"/": 200, "/slow": 200, "/fail": 500}.get(self.path, 404)
        self.reply(code, f"{code}\n")
        took = time.time() - started
        with LOCK:
            STATE["in_flight"] -= 1
            REQUESTS[(self.path if code != 404 else "other", code)] += 1
            STATE["sum"] += took
            STATE["count"] += 1
            BUCKET_COUNTS[next((i for i, b in enumerate(BUCKETS) if took <= b), len(BUCKETS))] += 1
        level = "error" if code >= 500 else "info"
        now = time.time()
        stamp = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(now)) + f".{int(now % 1 * 1000):03d}Z"
        LOG.write(f"ts={stamp} level={level} path={self.path} code={code} duration_ms={took * 1000:.0f}\n")


http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

Run:

python3 app.py 18000 app.log > app.out 2>&1 &
echo $! > app.pid
sleep 1
for path in / / / / / /slow /fail /fail /nope; do curl -s -o /dev/null -w "$path -> %{http_code}\n" "localhost:18000$path"; done
curl -s localhost:18000/metrics

Output of the tutorial's run:

/ -> 200
/ -> 200
/ -> 200
/ -> 200
/ -> 200
/slow -> 200
/fail -> 500
/fail -> 500
/nope -> 404
# HELP app_requests_total Requests handled, by path and status code.
# TYPE app_requests_total counter
app_requests_total{path="/",code="200"} 5
app_requests_total{path="/fail",code="500"} 2
app_requests_total{path="/slow",code="200"} 1
app_requests_total{path="other",code="404"} 1
# HELP app_in_flight_requests Requests that are being handled now.
# TYPE app_in_flight_requests gauge
app_in_flight_requests 0
# HELP app_request_duration_seconds Time to handle a request.
# TYPE app_request_duration_seconds histogram
app_request_duration_seconds_bucket{le="0.05"} 8
app_request_duration_seconds_bucket{le="0.1"} 8
app_request_duration_seconds_bucket{le="0.25"} 8
app_request_duration_seconds_bucket{le="0.5"} 9
app_request_duration_seconds_bucket{le="1.0"} 9
app_request_duration_seconds_bucket{le="+Inf"} 9
app_request_duration_seconds_sum 0.306769
app_request_duration_seconds_count 9
  • The /metrics page is plain text. The lines that start with # HELP and # TYPE are comments, which the format uses for help text and for the type of a metric Source 17সোর্স 17.
  • app_requests_total is a counter with the labels path and code. Its name ends in _total, which is the convention for counters Source 12সোর্স 12. The nine requests of the run gave the values 5, 1, 2, and 1. The tutorial's app counts a path that does not exist under the label other. That is the tutorial's own choice.
  • app_in_flight_requests is a gauge, a value that can go up and down Source 10সোর্স 10. Its value was 0 when the page was read.
  • app_request_duration_seconds is a histogram. Its buckets are cumulative counters Source 10সোর্স 10. Eight requests took 0.05 s or less, and all nine took 0.5 s or less. The sum was 0.306769 s, which is mostly the 0.3 s of /slow. The sum is different on every run.

2. Write the Prometheus files, and check them without a server. Save the scrape configuration as prometheus.yml:

global:
  scrape_interval: 5s
  evaluation_interval: 5s

rule_files:
  - rules.yml

alerting:
  alertmanagers:
    - static_configs:
        - targets: ["127.0.0.1:19093"]

scrape_configs:
  - job_name: app
    static_configs:
      - targets: ["127.0.0.1:18000"]

Save the rules as rules.yml:

groups:
  - name: app
    interval: 5s
    rules:
      - record: job:app_requests:rate1m
        expr: sum by (job) (rate(app_requests_total[1m]))
      - alert: AppHighErrorRatio
        expr: sum(rate(app_requests_total{code=~"5.."}[1m])) / sum(rate(app_requests_total[1m])) > 0.2
        for: 15s
        labels:
          severity: page
        annotations:
          summary: More than 20% of the requests fail.
      - alert: AppDown
        expr: up{job="app"} == 0
        for: 10s
        labels:
          severity: page
        annotations:
          summary: The app does not answer its scrapes.

Run:

promtool check config prometheus.yml
promtool check rules rules.yml

Output of the tutorial's run:

Checking prometheus.yml
  SUCCESS: 1 rule files found
 SUCCESS: prometheus.yml is valid prometheus config file syntax

Checking rules.yml
  SUCCESS: 3 rules found

Checking rules.yml
  SUCCESS: 3 rules found
  • The configuration has one job, app, with one static target, the app of step 1. The overview says that targets are discovered via service discovery or static configuration Source 8সোর্স 8. The block alerting points to the Alertmanager of step 5. The intervals of 5 s are the tutorial's own choice.
  • The first rule is a recording rule, job:app_requests:rate1m. Its expression takes the rate() first, and then aggregates with sum by (job), as the docs say Source 13সোর্স 13.
  • The alert AppHighErrorRatio divides the rate of the requests with a status code from 500 to 599 by the rate of all requests, and compares the result with 0.2. By default, a comparison between an instant vector and a scalar drops the elements for which it is false Source 40সোর্স 40. Their behavior can be modified by providing bool after the operator, which returns 0 or 1 for the value rather than filtering Source 40সোর্স 40. The for of 15 s means that the alert is pending until the expression has been returned for that long Source 14সোর্স 14.
  • The alert AppDown fires when up{job="app"} is 0, and up is 0 if the scrape failed Source 11সোর্স 11. Both alerts carry the label severity: page and an annotation summary Source 15সোর্স 15.
  • promtool check config checks if the config files are valid or not, and promtool check rules checks the rule files Source 26সোর্স 26. The first command printed SUCCESS for the configuration, and SUCCESS: 1 rule files found. The page of promtool lists a flag --syntax-only, which ignores the validation of the files and content that the config references Source 26সোর্স 26. The tutorial did not use that flag. The second command printed SUCCESS: 3 rules found. No Prometheus server was running in this step. The page on rules says that you can quickly check whether a rule file is syntactically correct without starting a Prometheus server, with promtool check rules Source 14সোর্স 14.

3. Unit-test the rules. Save the tests as rules.test.yml:

rule_files:
  - rules.yml
evaluation_interval: 5s

tests:
  - name: failing requests raise the error-ratio alert
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
      - series: 'app_requests_total{job="app", path="/fail", code="500"}'
        values: '0+5x24'
    alert_rule_test:
      - eval_time: 10s
        alertname: AppHighErrorRatio
        exp_alerts: []
      - eval_time: 1m
        alertname: AppHighErrorRatio
        exp_alerts:
          - exp_labels:
              severity: page
            exp_annotations:
              summary: More than 20% of the requests fail.
    promql_expr_test:
      - expr: job:app_requests:rate1m
        eval_time: 1m
        exp_samples:
          - labels: 'job:app_requests:rate1m{job="app"}'
            value: 3

  - name: healthy traffic does not raise it
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
    alert_rule_test:
      - eval_time: 1m
        alertname: AppHighErrorRatio
        exp_alerts: []

  - name: a target that stops answering raises AppDown
    interval: 5s
    input_series:
      - series: 'up{job="app", instance="127.0.0.1:18000"}'
        values: '1 1 1 0x20'
    alert_rule_test:
      - eval_time: 1m
        alertname: AppDown
        exp_alerts:
          - exp_labels:
              severity: page
              job: app
              instance: 127.0.0.1:18000
            exp_annotations:
              summary: The app does not answer its scrapes.

Save a test with a wrong expectation as bad.test.yml:

rule_files:
  - rules.yml
evaluation_interval: 5s

tests:
  - name: a wrong expectation (the rate is 3, the test says 4)
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
      - series: 'app_requests_total{job="app", path="/fail", code="500"}'
        values: '0+5x24'
    promql_expr_test:
      - expr: job:app_requests:rate1m
        eval_time: 1m
        exp_samples:
          - labels: 'job:app_requests:rate1m{job="app"}'
            value: 4

Run:

promtool test rules rules.test.yml; echo "exit status: $?"
promtool test rules bad.test.yml; echo "exit status: $?"

Output of the tutorial's run:

Processing test file: rules.test.yml
  SUCCESS

exit status: 0
Processing test file: bad.test.yml
  FAILED:
    expr: "job:app_requests:rate1m", time: 1m,
        exp: {__name__="job:app_requests:rate1m", job="app"} 4E+00
        got: {__name__="job:app_requests:rate1m", job="app"} 3E+00


exit status: 1
  • The promtool test rules command runs unit tests for rules Source 26সোর্স 26. A test file lists the rule files to consider Source 16সোর্স 16.
  • The first test group feeds two counters into the rules. 0+10x24 starts at 0 and adds 10 for 24 more samples, and 0+5x24 adds 5. The docs read it as "series starts at a, then n further samples incrementing by b" Source 16সোর্স 16. With one sample every 5 s, the counters grow by 2 and 1 per second, so the sum of the rates is 3.
  • At 10 s, the test exp_alerts: [] expects that AppHighErrorRatio is not firing. At 1 m, it expects one alert, with the labels and the annotation of the rule. The group also checks that job:app_requests:rate1m is 3 at 1 m.
  • The second group has only the good counter, and expects no alert. The third group gives up the values 1 1 1 0x20, and expects AppDown at 1 m.
  • The first file printed SUCCESS and ended with the exit status 0. The second file expects 4, and the real value is 3. The output of the failure shows the expression, the time, the expected sample (exp), and the sample that the rules gave (got), and the exit status was 1. The output of the failure and the exit statuses are from the tutorial's run.

4. Write the Alertmanager configuration, and test the routing without a server. Save it as alertmanager.yml:

route:
  receiver: team-default
  group_by: [alertname]
  group_wait: 5s
  group_interval: 10s
  repeat_interval: 1h
  routes:
    - matchers:
        - severity="page"
      receiver: team-oncall

receivers:
  - name: team-default
  - name: team-oncall

Run:

amtool check-config alertmanager.yml
amtool config routes show --config.file=alertmanager.yml
amtool config routes test --config.file=alertmanager.yml severity=page alertname=AppDown
amtool config routes test --config.file=alertmanager.yml severity=ticket alertname=AppHighErrorRatio

Output of the tutorial's run:

Checking 'alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 0 inhibit rules
 - 2 receivers
 - 0 templates

Routing tree:
.
└── default-route  receiver: team-default
    └── {severity="page"}  receiver: team-oncall

team-oncall
team-default
  • The root route sends alerts to the receiver team-default and groups them by alertname. One child route sends the alerts with severity="page" to team-oncall. The two receivers in the file have no integration settings. The values 5s, 10s, and 1h are the tutorial's own choice. The docs describe group_wait as how long to wait before sending the first notification for a new group Source 24সোর্স 24, and repeat_interval as how long to wait before repeating the last notification Source 24সোর্স 24.
  • Every alert enters the routing tree at the top-level route and then traverses the child nodes Source 24সোর্স 24.
  • amtool check-config printed SUCCESS, and it counted the route, 0 inhibit rules, 2 receivers, and 0 templates. No Alertmanager server was running yet, because step 5 starts it. The configuration page shows amtool check-config for the check of UTF-8 strict mode Source 24সোর্স 24. It says that you do not need a running Alertmanager server for that check Source 24সোর্স 24.
  • amtool config routes show printed the tree of the routes. amtool config routes test printed team-oncall for an alert with severity=page, and team-default for an alert with severity=ticket. The README of Alertmanager says that amtool can visualize the routes of a configuration as a text tree Source 25সোর্স 25. It says that you can also use it to test the routing, by passing it the label set of an alert Source 25সোর্স 25. The README writes the two commands as amtool config routes Source 25সোর্স 25 and amtool config routes test Source 25সোর্স 25. The tutorial ran the first as config routes show, and the README does not write it that way.

5. Start the servers, and ask Prometheus questions. Run:

alertmanager --config.file=alertmanager.yml --storage.path=am-data --web.listen-address=127.0.0.1:19093 --cluster.listen-address= > am.out 2>&1 &
echo $! > am.pid
prometheus --config.file=prometheus.yml --storage.tsdb.path=prom-data --web.listen-address=127.0.0.1:19090 > prom.out 2>&1 &
echo $! > prom.pid
until curl -sf localhost:19090/-/ready; do sleep 1; done
sleep 12
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=up'; echo
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=sum by (code) (app_requests_total)'; echo
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=histogram_quantile(0.9, sum by (le) (app_request_duration_seconds_bucket))'; echo

Output of the tutorial's run:

Prometheus Server is Ready.
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","instance":"127.0.0.1:18000","job":"app"},"value":[1795086690.402,"1"]}]}}
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"code":"200"},"value":[1795086690.416,"6"]},{"metric":{"code":"500"},"value":[1795086690.416,"2"]},{"metric":{"code":"404"},"value":[1795086690.416,"1"]}]}}
{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1795086690.431,"0.2749999999999999"]}]}}
  • The flag --config.file is the Prometheus configuration file path Source 29সোর্স 29. The flag --storage.tsdb.path is the base path for metrics storage Source 29সোর্স 29. The flag --web.listen-address is the address to listen on for UI, API, and telemetry Source 29সোর্স 29. The data folders, and the ports 19090 and 19093, are the tutorial's own choice.
  • Setting --cluster.listen-address= prevents Alertmanager from listening to incoming peer requests Source 25সোর্স 25. The tutorial set it. The sockets of the run show no gossip port.
  • /-/ready printed Prometheus Server is Ready. That endpoint returns 200 when Prometheus is ready to serve traffic Source 28সোর্স 28. The until loop of the tutorial waits for it.
  • The API response format is JSON Source 27সোর্স 27. The endpoint /api/v1/query evaluates an instant query at a single point in time Source 27সোর্স 27.
  • The query up returned one series, with the value "1". That means the instance was healthy, that is, reachable Source 11সোর্স 11.
  • The query sum by (code) (app_requests_total) returned 6 for the code 200, 2 for 500, and 1 for 404. They are the totals of step 1: five requests to / and one to /slow made six 200s.
  • The query histogram_quantile(0.9, sum by (le) (app_request_duration_seconds_bucket)) returned 0.2749999999999999. Eight of the nine requests were in the buckets up to 0.25 s. The docs say that the φ-quantile is the observation value that ranks at number φ*N among the N observations Source 20সোর্স 20. For φ = 0.9 and N = 9, the rank is 8.1, so the tutorial's own arithmetic puts the answer in the bucket from 0.25 to 0.5, which holds the ninth request. The function interpolates the quantile value within the bucket that it falls into Source 13সোর্স 13. For classic histograms, it assumes a uniform distribution of observations within the bucket Source 13সোর্স 13. That gives 0.25 plus 0.1 times 0.25, which is 0.275.
  • The tutorial left out rate() in that query, so the answer covers all nine requests since the app started. The docs use the rate() function to specify the time window Source 13সোর্স 13. That is the tutorial's own choice, so that the number can be repeated.

6. Make the alerts fire, and look at them in Alertmanager. The step defines helper functions that the tutorial wrote. alerts prints the name and the state of each alert from the endpoint /api/v1/alerts. wait_for loops until a given line shows. In the background, a loop sends two failing requests for every good one. Run:

alerts() { curl -s localhost:19090/api/v1/alerts | python3 -c 'import json, sys; [print(a["labels"]["alertname"], a["state"]) for a in json.load(sys.stdin)["data"]["alerts"]]'; }
wait_for() { until alerts | grep -q "$1"; do sleep 1; done; echo "--- Prometheus reports: $1"; alerts; }
AM="amtool --alertmanager.url=http://127.0.0.1:19093"

# traffic with two failing requests for every good one, in the background
( while true; do curl -s -o /dev/null localhost:18000/; curl -s -o /dev/null localhost:18000/fail; curl -s -o /dev/null localhost:18000/fail; sleep 1; done ) &
echo $! > traffic.pid
wait_for "AppHighErrorRatio pending"
wait_for "AppHighErrorRatio firing"
kill "$(cat traffic.pid)"
until $AM alert query | grep -q AppHighErrorRatio; do sleep 1; done
echo "--- Alertmanager received it:"; $AM alert query
$AM silence add alertname=AppHighErrorRatio --author=tutorial --comment="practice run" --duration=10m
echo "--- after the silence:"; $AM alert query; echo "(the line above ends the list of active alerts)"; $AM alert query --silenced

# stop the app: the scrape fails and up becomes 0
kill "$(cat app.pid)"
wait_for "AppDown pending"
wait_for "AppDown firing"
until $AM alert query | grep -q AppDown; do sleep 1; done
echo "--- Alertmanager received it:"; $AM alert query

Output of the tutorial's run:

--- Prometheus reports: AppHighErrorRatio pending
AppHighErrorRatio pending
--- Prometheus reports: AppHighErrorRatio firing
AppHighErrorRatio firing
--- Alertmanager received it:
Alertname          Starts At                Summary                              State   
AppHighErrorRatio  2026-11-19 11:11:51 UTC  More than 20% of the requests fail.  active  
d009a065-d5f7-4960-9a46-5f79f358f22e
--- after the silence:
Alertname  Starts At  Summary  State  
(the line above ends the list of active alerts)
Alertname          Starts At                Summary                              State       
AppHighErrorRatio  2026-11-19 11:11:51 UTC  More than 20% of the requests fail.  suppressed  
--- Prometheus reports: AppDown pending
AppHighErrorRatio firing
AppDown pending
--- Prometheus reports: AppDown firing
AppHighErrorRatio firing
AppDown firing
--- Alertmanager received it:
Alertname  Starts At                Summary                               State   
AppDown    2026-11-19 11:12:11 UTC  The app does not answer its scrapes.  active  
  • The /alerts endpoint returns a list of all active alerts Source 27সোর্স 27.
  • AppHighErrorRatio was reported as pending, and later as firing. An alert is pending until it has been returned for the for time Source 14সোর্স 14. While the app answered 500, this was the only alert in the list.
  • amtool alert query printed the alert with the state active. The Starts At column is in UTC. The tutorial's time zone was +06, so the time of the alert is six hours behind the clock of the machine.
  • The README shows amtool silence add alertname=Test_Alert Source 25সোর্স 25. The Alertmanager page says that silences are configured in the web interface Source 23সোর্স 23. The tutorial used amtool instead, and it printed the ID of the new silence. After that, amtool alert query listed no active alert, and with --silenced it listed the alert with the state suppressed. No page that the tutorial read describes the flag --silenced or the state suppressed.
  • After the app was stopped, Prometheus reported AppDown as pending, and later as firing. Its up was 0, because the scrape failed Source 11সোর্স 11. AppHighErrorRatio was still firing at that time, and the tutorial did not wait to see when it ends.
  • Alertmanager listed AppDown as active. The other alert was silenced, so it was not in the list.

7. Start Loki, send the log lines of the app to it, and query them. The Loki configuration comes from the docs. The page lists a complete configuration to deploy Loki backed by the filesystem Source 37সোর্স 37. The tutorial changed the ports, and the folder, which is loki-data here and /tmp/loki on the page Source 37সোর্স 37. It also set the HTTP listen address, and it added analytics with reporting_enabled: false. The configuration reference describes that setting as "Enable anonymous usage reporting" Source 38সোর্স 38. Save it as loki.yml:

auth_enabled: false

server:
  http_listen_address: 127.0.0.1
  http_listen_port: 13100
  grpc_listen_port: 19096

common:
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory
  replication_factor: 1
  path_prefix: loki-data

schema_config:
  configs:
    - from: 2020-05-15
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

storage_config:
  filesystem:
    directory: loki-data/chunks

analytics:
  reporting_enabled: false

The sender push.py is the tutorial's own. It reads the lines of app.log, and sends them as one stream with the label job="app":

"""Send the lines of an app log to Loki, as one stream with the label job="app".

  python3 push.py app.log http://127.0.0.1:13100
Each line starts with ts=<UTC time with milliseconds>. That time becomes the timestamp of the entry in Loki.
"""
import datetime
import json
import re
import sys
import urllib.request

path, base = sys.argv[1], sys.argv[2]
values = []
for line in open(path, encoding="utf-8").read().splitlines():
    stamp = re.match(r"ts=(\S+)", line).group(1)
    when = datetime.datetime.fromisoformat(stamp)
    values.append([str(int(when.timestamp() * 1000) * 1_000_000), line])
body = json.dumps({"streams": [{"stream": {"job": "app"}, "values": values}]}).encode()
request = urllib.request.Request(base + "/loki/api/v1/push", data=body, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request) as response:
    print(f"pushed {len(values)} lines, HTTP status {response.status}")

Run:

loki -config.file=loki.yml > loki.out 2>&1 &
echo $! > loki.pid
until [ "$(curl -s -o /dev/null -w '%{http_code}' localhost:13100/ready)" = 200 ]; do sleep 2; done
curl -s localhost:13100/ready
python3 push.py app.log http://127.0.0.1:13100
# a helper that prints the result and leaves out the "stats" field of the response
lq() { curl -s --get "localhost:13100/loki/api/v1/$1" --data-urlencode "query=$2" "${@:3}" | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["status"], d["data"]["resultType"]); print(json.dumps(d["data"]["result"]))'; }
curl -s localhost:13100/loki/api/v1/labels; echo
lq query_range '{job="app"} |= "code=500"' --data-urlencode limit=2
lq query 'sum by (path) (count_over_time({job="app"} | logfmt | code >= 500 [1h]))'

Output of the tutorial's run:

ready
pushed 69 lines, HTTP status 204
{"status":"success","data":["job","service_name"]}

success streams
[{"stream": {"detected_level": "error", "job": "app", "service_name": "app"}, "values": [["1795086711780000000", "ts=2026-11-19T11:11:51.780Z level=error path=/fail code=500 duration_ms=1"], ["1795086711754000000", "ts=2026-11-19T11:11:51.754Z level=error path=/fail code=500 duration_ms=0"]]}]
success vector
[{"metric": {"path": "/fail"}, "value": [1795086751.347, "42"]}]
  • /ready printed ready. That endpoint returns HTTP 200 when the Loki instance is ready to accept traffic Source 36সোর্স 36. The loop of the tutorial waits for the status 200.
  • push.py sent 69 lines, and the endpoint answered with the status 204. The timestamp of each entry is a string, as the API needs Source 36সোর্স 36.
  • The labels endpoint returned job and service_name. The tutorial sent only job. Loki added service_name itself, with the value app, which is the value of job. If no service_name is on the stream, Loki looks for the first non-empty value from a list of labels, in order Source 32সোর্স 32.
  • The stream of the first result also has the label detected_level, with the value error. The configuration reference says that Loki can discover and add log levels during ingestion, if not present already Source 38সোর্স 38. The tutorial did not set it, and no page that the tutorial read names the key detected_level.
  • The log query {job="app"} |= "code=500" selects the stream, and keeps the lines with code=500. A line filter expression does a distributed grep over the log streams that match, and discards the lines that do not match Source 34সোর্স 34. The limit=2 kept two entries. The parameter limit is the max number of entries to return, and it defaults to 100 Source 36সোর্স 36.
  • The metric query sum by (path) (count_over_time({job="app"} | logfmt | code >= 500 [1h])) returned one series, path="/fail", with the value 42. The function count_over_time counts the entries for each log stream within the given range Source 35সোর্স 35. The logfmt stage parses each log line to extract more labels, and the next stage filters with them Source 34সোর্স 34. The log file had 42 lines for /fail, so the two numbers agree. The number differs on every run, because it depends on how many requests the loop of step 6 sent.
  • The helper lq leaves out the field stats of the response. Query endpoints return a set of statistics about the query execution Source 36সোর্স 36.

8. Pass a trace context from one service to another. The script has two services in one process, service-a and service-b. The dictionary headers stands in for the HTTP request between them, so no network is used. The script uses the ConsoleSpanExporter of the SDK, which is included in the opentelemetry-sdk package Source 5সোর্স 5. It passes the context by hand, as the Python docs show Source 4সোর্স 4. The same page says to use instrumentation libraries to propagate context Source 4সোর্স 4. The function one_line and the five checks are the tutorial's own. Save the script as otel_demo.py:

"""Trace context propagation with the OpenTelemetry Python SDK: two "services" in one process.

The dictionary `headers` stands in for the HTTP request between them. Each span is printed on one line when it ends.
"""
import json
import re

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

SPANS = []


def one_line(span):
    d = json.loads(span.to_json())
    row = {"name": d["name"], "trace_id": d["context"]["trace_id"], "span_id": d["context"]["span_id"], "parent_id": d["parent_id"]}
    SPANS.append(row)
    return json.dumps(row) + "\n"


provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("practice")
propagator = TraceContextTextMapPropagator()


def service_b(headers):
    context = propagator.extract(carrier=headers)
    with tracer.start_as_current_span("service-b handles the request", context=context):
        pass


print("case 1: service A sends the traceparent header")
with tracer.start_as_current_span("service-a calls service-b"):
    headers = {}
    propagator.inject(headers)
    print("traceparent:", headers["traceparent"])
    service_b(headers)

print("case 2: the header is lost on the way")
with tracer.start_as_current_span("service-a calls service-b, no header"):
    service_b({})

b1, a1, b2, a2 = SPANS  # a span is printed when it ends, so each service-b span comes before its service-a span
print("check 1: header has the form 00-<32 hex>-<16 hex>-<2 hex>:", bool(re.fullmatch(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", headers["traceparent"])))
print("check 2: case 1, both spans share one trace id:", a1["trace_id"] == b1["trace_id"])
print("check 3: case 1, the parent of the service-b span is the service-a span:", b1["parent_id"] == a1["span_id"])
print("check 4: case 2, the trace ids differ:", a2["trace_id"] != b2["trace_id"])
print("check 5: case 2, the service-b span has no parent:", b2["parent_id"] is None)

Run:

venv/bin/python otel_demo.py

Output of the tutorial's run:

case 1: service A sends the traceparent header
traceparent: 00-0476e04404089b682e7a22e120886d1e-d4f79e01e18511ac-03
{"name": "service-b handles the request", "trace_id": "0x0476e04404089b682e7a22e120886d1e", "span_id": "0x60a1a9c5df67ed51", "parent_id": "0xd4f79e01e18511ac"}
{"name": "service-a calls service-b", "trace_id": "0x0476e04404089b682e7a22e120886d1e", "span_id": "0xd4f79e01e18511ac", "parent_id": null}
case 2: the header is lost on the way
{"name": "service-b handles the request", "trace_id": "0x20c17ac1fac019492a3ea81ed585d55e", "span_id": "0xf955daacc6d0807c", "parent_id": null}
{"name": "service-a calls service-b, no header", "trace_id": "0x180f73c286f70edb200fa915c2cd2174", "span_id": "0x95f1c3f4063851ef", "parent_id": null}
check 1: header has the form 00-<32 hex>-<16 hex>-<2 hex>: True
check 2: case 1, both spans share one trace id: True
check 3: case 1, the parent of the service-b span is the service-a span: True
check 4: case 2, the trace ids differ: True
check 5: case 2, the service-b span has no parent: True
  • In case 1, service A put the context into headers. The header has the four fields Source 6সোর্স 6. Its last field was 03. The right-most bit of the flags, when set, denotes that the caller may have recorded trace data Source 6সোর্স 6. The page also says that the flags are a bit field, and that you cannot read them as a number Source 6সোর্স 6. So 03 means that the right-most bit is set, and that another bit is set too. No page that the tutorial read names that other bit.
  • The two spans of case 1 have the same trace_id. The parent_id of the span of service B is the span_id of the span of service A. The span of service A has a trace_id but no parent_id, and that is how you know that it is a root span Source 41সোর্স 41.
  • In case 2, the header was lost, and service B started a new trace: its trace_id is different, and it has no parent. The W3C page says that, when no traceparent header is received, the vendor creates a new trace-id and parent-id that represents the current request Source 6সোর্স 6. The service-A span of case 2 has a third trace id, because it is a new root span too.
  • The five checks of the script printed True. Case 2 shows what broken propagation looks like: two traces with different ids, where one trace was expected.

বাংলা ব্যাখ্যা

টিউটোরিয়াল ১ থেকে ৮ নম্বর ধাপ চালিয়েছে 2026-11-19 তারিখে 17:11-এ (+06), Linux 7.0.0-43-generic-এ, Prometheus 3.16.0, Alertmanager 0.35.0, Loki 3.7.10, OpenTelemetry SDK 1.45.2, app আর সহায়ক script-এর জন্য Python 3.14.4, SDK-র জন্য Python 3.14.9 আর bash 5.3.9 দিয়ে। এই page-এর output টিউটোরিয়ালের run থেকে নেওয়া। প্রতিটা ধাপ চলেছে নিজের shell-এ, practice folder-এর একটা কপিতে, একটা নতুন, খালি HOME দিয়ে। page-এ run-এর folder দেখানো হয়েছে /work নামে, আর SDK-র virtual environment /venv নামে।

app, Prometheus, Alertmanager আর Loki-র HTTP port 127.0.0.1-এ শোনে। Loki-র gRPC port তার default address রেখেছে। এই এক-process সেটআপে সেই port-কে 127.0.0.1-এ রাখার কোনো setting টিউটোরিয়াল পায়নি। সে দুটো চেষ্টা করেছে। grpc_listen_address: 127.0.0.1 দিয়ে প্রথম Loki query কোনো উত্তর পায়নি। instance_interface_names: [lo] দিয়ে Loki শুরুতেই no useable address found for interfaces [lo] বলে থেমে গেছে। টিউটোরিয়ালের run-এ server-গুলো শুনেছে *:19096 (Loki, gRPC), 127.0.0.1:13100 (Loki), 127.0.0.1:19090 (Prometheus) আর 127.0.0.1:19093 (Alertmanager)-এ। ৭ নম্বর ধাপ এমন machine আর network-এ চালান, যাকে আপনি বিশ্বাস করেন, কারণ Loki-র gRPC port সব address-এ connection নেয়। কোনো ধাপের cloud account, container বা দূরের host লাগে না।

যে সিদ্ধান্ত কোনো source দেয় না, সেগুলো টিউটোরিয়ালের নিজের: app, file-গুলোর নাম, file-এর ভেতরের নাম, port, data folder, ছোট ব্যবধান (5s, 15s আর 10s), ধাপগুলোর traffic, ৩ নম্বর ধাপের ভুল test, severity label আর receiver-এর নাম, এবং ৬ ও ৭ নম্বর ধাপের সহায়ক function। টিউটোরিয়াল Grafana, OpenTelemetry Collector, Grafana Alloy বা Promtail, Jaeger-এর মতো tracing backend, সত্যিকারের receiver-এ notification, inhibition rule, high availability বা remote storage চালায়নি। সেই অংশগুলো শুধু docs থেকে বর্ণনা করা।

tool-গুলো install করুন। Prometheus docs বলে, বেশির ভাগ official Prometheus component-এর জন্য তারা precompiled binary দেয় Source 30সোর্স 30। docs আরও বলে, Docker-এ Prometheus চালানো docker run -p 9090:9090 prom/prometheus লেখার মতোই সহজ Source 30সোর্স 30। Loki docs বলে, Loki যাচাই, test বা development করলে আপনি Docker বা Docker Compose দিয়ে Loki আর Alloy install করতে পারেন Source 39সোর্স 39। টিউটোরিয়াল কোনো Docker page-ই অনুসরণ করেনি। সে একজন user-এর জন্য release binary install করেছে, যাতে machine-এর Docker host-এ কোনো container বা image না লাগে। এটা টিউটোরিয়ালের নিজের সিদ্ধান্ত।

2026-11-19 তারিখে 16:48-এ টিউটোরিয়ালের install script দুই project-এর GitHub release page থেকে Prometheus 3.16.0 আর Loki 3.7.10-র release archive download করেছে। 16:56-এ সে Alertmanager 0.35.0-এর জন্য একই কাজ করেছে। প্রতিটা archive-এর SHA-256 সে একই release-এর checksum file-এর মানের সঙ্গে মিলিয়েছে, আর দুটো মান এক ছিল। archive-গুলো শুরু হয় 68727009 (Prometheus), 200e74f7 (Loki) আর 6c7752a9 (Alertmanager) দিয়ে। এই যাচাইয়ের সীমা আছে। checksum file আসে archive-এর একই host থেকে, আর সেদিন release page তার পাশে কোনো signature file তালিকাভুক্ত করেনি। তাই যাচাই একটা নষ্ট বা বদলে দেওয়া archive ধরে, কিন্তু কে সেটা বানিয়েছে তা প্রমাণ করে না। script prometheus, promtool, alertmanager, amtool আর loki ~/.local/bin-এ রেখেছে।

OpenTelemetry-র জন্য টিউটোরিয়াল Python 3.14.9 দিয়ে একটা virtual environment বানিয়েছে আর 16:56-এ তাতে opentelemetry-sdk 1.45.2 install করেছে। সে আগে wheel download করেছে, আর তার SHA-256 (যা ff974ea7 দিয়ে শুরু) মিলিয়েছে সেই মানের সঙ্গে, যা PyPI JSON API সেই file-এর জন্য তালিকাভুক্ত করে। দুটো মান এক ছিল। dependency-গুলো pip দিয়ে PyPI থেকে HTTPS-এ install হয়েছে, hash যাচাই ছাড়া। এসবই টিউটোরিয়ালের নিজের সিদ্ধান্ত।

১. একটা ছোট web app চালু করুন, আর তার metric পড়ুন। app-টা টিউটোরিয়ালের নিজের, এই পাঠের জন্য লেখা। সে শুধু standard library ব্যবহার করে। সে path আর status code ধরে অনুরোধ গোনে, প্রতিটা অনুরোধের সময় মাপে, আর প্রতি অনুরোধে একটা log লাইন লেখে। / 200 দেয়, /slow ০.৩ সেকেন্ড পরে 200 দেয়, /fail 500 দেয়, আর অন্য যেকোনো path 404 দেয়। এটা app.py নামে save করুন:

"""A tiny web app for the practice run: it counts and times its own requests and shows them at /metrics.

  python3 app.py PORT LOGFILE

The routes are /, /slow (sleeps 0.3 s), /fail (answers 500), /metrics, and anything else (404). It uses only the
standard library. The metrics are written in the text format of Prometheus, and each request is also logged as one
line of key=value pairs.
"""
import http.server
import sys
import threading
import time
from collections import Counter

BUCKETS = (0.05, 0.1, 0.25, 0.5, 1.0)
LOCK = threading.Lock()
REQUESTS = Counter()  # (path, code) -> number of requests
BUCKET_COUNTS = [0] * (len(BUCKETS) + 1)  # observations per bucket (the last one is above 1.0)
STATE = {"sum": 0.0, "count": 0, "in_flight": 0}
PORT, LOGFILE = int(sys.argv[1]), sys.argv[2]
LOG = open(LOGFILE, "a", buffering=1, encoding="utf-8")


def render():
    lines = ["# HELP app_requests_total Requests handled, by path and status code.", "# TYPE app_requests_total counter"]
    for (path, code), n in sorted(REQUESTS.items()):
        lines.append(f'app_requests_total{{path="{path}",code="{code}"}} {n}')
    lines += ["# HELP app_in_flight_requests Requests that are being handled now.", "# TYPE app_in_flight_requests gauge",
              f"app_in_flight_requests {STATE['in_flight']}",
              "# HELP app_request_duration_seconds Time to handle a request.", "# TYPE app_request_duration_seconds histogram"]
    cumulative = 0
    for bound, n in zip(BUCKETS, BUCKET_COUNTS):
        cumulative += n
        lines.append(f'app_request_duration_seconds_bucket{{le="{bound}"}} {cumulative}')
    lines += [f'app_request_duration_seconds_bucket{{le="+Inf"}} {STATE["count"]}',
              f'app_request_duration_seconds_sum {STATE["sum"]:.6f}', f'app_request_duration_seconds_count {STATE["count"]}']
    return "\n".join(lines) + "\n"


class Handler(http.server.BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def reply(self, code, body, ctype="text/plain; charset=utf-8"):
        data = body.encode()
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/metrics":
            with LOCK:
                self.reply(200, render(), "text/plain; version=0.0.4; charset=utf-8")
            return
        started = time.time()
        with LOCK:
            STATE["in_flight"] += 1
        if self.path == "/slow":
            time.sleep(0.3)
        code = {"/": 200, "/slow": 200, "/fail": 500}.get(self.path, 404)
        self.reply(code, f"{code}\n")
        took = time.time() - started
        with LOCK:
            STATE["in_flight"] -= 1
            REQUESTS[(self.path if code != 404 else "other", code)] += 1
            STATE["sum"] += took
            STATE["count"] += 1
            BUCKET_COUNTS[next((i for i, b in enumerate(BUCKETS) if took <= b), len(BUCKETS))] += 1
        level = "error" if code >= 500 else "info"
        now = time.time()
        stamp = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(now)) + f".{int(now % 1 * 1000):03d}Z"
        LOG.write(f"ts={stamp} level={level} path={self.path} code={code} duration_ms={took * 1000:.0f}\n")


http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

চালান:

python3 app.py 18000 app.log > app.out 2>&1 &
echo $! > app.pid
sleep 1
for path in / / / / / /slow /fail /fail /nope; do curl -s -o /dev/null -w "$path -> %{http_code}\n" "localhost:18000$path"; done
curl -s localhost:18000/metrics

টিউটোরিয়ালের run-এর output:

/ -> 200
/ -> 200
/ -> 200
/ -> 200
/ -> 200
/slow -> 200
/fail -> 500
/fail -> 500
/nope -> 404
# HELP app_requests_total Requests handled, by path and status code.
# TYPE app_requests_total counter
app_requests_total{path="/",code="200"} 5
app_requests_total{path="/fail",code="500"} 2
app_requests_total{path="/slow",code="200"} 1
app_requests_total{path="other",code="404"} 1
# HELP app_in_flight_requests Requests that are being handled now.
# TYPE app_in_flight_requests gauge
app_in_flight_requests 0
# HELP app_request_duration_seconds Time to handle a request.
# TYPE app_request_duration_seconds histogram
app_request_duration_seconds_bucket{le="0.05"} 8
app_request_duration_seconds_bucket{le="0.1"} 8
app_request_duration_seconds_bucket{le="0.25"} 8
app_request_duration_seconds_bucket{le="0.5"} 9
app_request_duration_seconds_bucket{le="1.0"} 9
app_request_duration_seconds_bucket{le="+Inf"} 9
app_request_duration_seconds_sum 0.306769
app_request_duration_seconds_count 9
  • /metrics page সাধারণ text। # HELP আর # TYPE দিয়ে শুরু হওয়া লাইনগুলো comment, যা format help text আর metric-এর type-এর জন্য ব্যবহার করে Source 17সোর্স 17।
  • app_requests_total একটা counter, যার label path আর code। তার নাম _total দিয়ে শেষ, যা counter-এর প্রচলিত রীতি Source 12সোর্স 12। run-এর নয়টা অনুরোধ মান দিয়েছে ৫, ১, ২ আর ১। টিউটোরিয়ালের app এমন path-কে, যা নেই, other label-এর নিচে গোনে। এটা টিউটোরিয়ালের নিজের সিদ্ধান্ত।
  • app_in_flight_requests একটা gauge, যে মান ওঠানামা করতে পারে Source 10সোর্স 10। page পড়ার সময় তার মান ছিল 0।
  • app_request_duration_seconds একটা histogram। তার bucket-গুলো জমা হওয়া counter Source 10সোর্স 10। আটটা অনুরোধ ০.০৫ সেকেন্ড বা তার কম নিয়েছে, আর নয়টাই ০.৫ সেকেন্ড বা তার কম নিয়েছে। যোগফল ছিল 0.306769 সেকেন্ড, যার বেশির ভাগই /slow-এর ০.৩ সেকেন্ড। যোগফল প্রতিটা run-এ আলাদা হয়।

২. Prometheus-এর file লিখুন, আর server ছাড়াই যাচাই করুন। scrape configuration prometheus.yml নামে save করুন:

global:
  scrape_interval: 5s
  evaluation_interval: 5s

rule_files:
  - rules.yml

alerting:
  alertmanagers:
    - static_configs:
        - targets: ["127.0.0.1:19093"]

scrape_configs:
  - job_name: app
    static_configs:
      - targets: ["127.0.0.1:18000"]

rule-গুলো rules.yml নামে save করুন:

groups:
  - name: app
    interval: 5s
    rules:
      - record: job:app_requests:rate1m
        expr: sum by (job) (rate(app_requests_total[1m]))
      - alert: AppHighErrorRatio
        expr: sum(rate(app_requests_total{code=~"5.."}[1m])) / sum(rate(app_requests_total[1m])) > 0.2
        for: 15s
        labels:
          severity: page
        annotations:
          summary: More than 20% of the requests fail.
      - alert: AppDown
        expr: up{job="app"} == 0
        for: 10s
        labels:
          severity: page
        annotations:
          summary: The app does not answer its scrapes.

চালান:

promtool check config prometheus.yml
promtool check rules rules.yml

টিউটোরিয়ালের run-এর output:

Checking prometheus.yml
  SUCCESS: 1 rule files found
 SUCCESS: prometheus.yml is valid prometheus config file syntax

Checking rules.yml
  SUCCESS: 3 rules found

Checking rules.yml
  SUCCESS: 3 rules found
  • configuration-এ একটা job, app, আর একটা static target, ১ নম্বর ধাপের app। overview বলে, target পাওয়া যায় service discovery বা static configuration দিয়ে Source 8সোর্স 8। alerting block ৫ নম্বর ধাপের Alertmanager-কে দেখায়। ৫ সেকেন্ডের ব্যবধান টিউটোরিয়ালের নিজের সিদ্ধান্ত।
  • প্রথম rule একটা recording rule, job:app_requests:rate1m। তার expression আগে rate() নেয়, তারপর sum by (job) দিয়ে aggregate করে, docs যেমন বলে Source 13সোর্স 13।
  • AppHighErrorRatio alert 500 থেকে 599 status code-এর অনুরোধের rate-কে সব অনুরোধের rate দিয়ে ভাগ করে, আর ফলকে 0.2-এর সঙ্গে তুলনা করে। ডিফল্টভাবে, একটা instant vector আর একটা scalar-এর মধ্যে তুলনায় যে element-এর ফল false, সেগুলো বাদ পড়ে Source 40সোর্স 40। operator-এর পরে bool দিয়ে তাদের আচরণ বদলানো যায়, তখন তারা filter না করে মান হিসেবে 0 বা 1 ফেরত দেয় Source 40সোর্স 40। for-এর ১৫ সেকেন্ডের মানে, expression এত সময় ধরে ফেরত না আসা পর্যন্ত alert pending থাকে Source 14সোর্স 14।
  • AppDown alert firing হয় যখন up{job="app"}-এর মান 0, আর up 0 হয় scrape ব্যর্থ হলে Source 11সোর্স 11। দুটো alert-এই severity: page label আর একটা summary annotation আছে Source 15সোর্স 15।
  • promtool check config দেখে config file বৈধ কি না, আর promtool check rules দেখে rule file Source 26সোর্স 26। প্রথম command configuration-এর জন্য SUCCESS ছেপেছে, আর SUCCESS: 1 rule files found। promtool-এর page একটা flag --syntax-only তালিকাভুক্ত করে, যা config যে file আর content-কে নির্দেশ করে সেগুলোর যাচাই উপেক্ষা করে Source 26সোর্স 26। টিউটোরিয়াল সেই flag ব্যবহার করেনি। দ্বিতীয় command ছেপেছে SUCCESS: 3 rules found। এই ধাপে কোনো Prometheus server চালু ছিল না। rule-এর page বলে, Prometheus server চালু না করেই promtool check rules দিয়ে আপনি দ্রুত দেখে নিতে পারেন একটা rule file সিনট্যাক্সের দিক থেকে ঠিক কি না Source 14সোর্স 14।

৩. rule-গুলোর unit test করুন। test-গুলো rules.test.yml নামে save করুন:

rule_files:
  - rules.yml
evaluation_interval: 5s

tests:
  - name: failing requests raise the error-ratio alert
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
      - series: 'app_requests_total{job="app", path="/fail", code="500"}'
        values: '0+5x24'
    alert_rule_test:
      - eval_time: 10s
        alertname: AppHighErrorRatio
        exp_alerts: []
      - eval_time: 1m
        alertname: AppHighErrorRatio
        exp_alerts:
          - exp_labels:
              severity: page
            exp_annotations:
              summary: More than 20% of the requests fail.
    promql_expr_test:
      - expr: job:app_requests:rate1m
        eval_time: 1m
        exp_samples:
          - labels: 'job:app_requests:rate1m{job="app"}'
            value: 3

  - name: healthy traffic does not raise it
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
    alert_rule_test:
      - eval_time: 1m
        alertname: AppHighErrorRatio
        exp_alerts: []

  - name: a target that stops answering raises AppDown
    interval: 5s
    input_series:
      - series: 'up{job="app", instance="127.0.0.1:18000"}'
        values: '1 1 1 0x20'
    alert_rule_test:
      - eval_time: 1m
        alertname: AppDown
        exp_alerts:
          - exp_labels:
              severity: page
              job: app
              instance: 127.0.0.1:18000
            exp_annotations:
              summary: The app does not answer its scrapes.

ভুল প্রত্যাশার একটা test bad.test.yml নামে save করুন:

rule_files:
  - rules.yml
evaluation_interval: 5s

tests:
  - name: a wrong expectation (the rate is 3, the test says 4)
    interval: 5s
    input_series:
      - series: 'app_requests_total{job="app", path="/", code="200"}'
        values: '0+10x24'
      - series: 'app_requests_total{job="app", path="/fail", code="500"}'
        values: '0+5x24'
    promql_expr_test:
      - expr: job:app_requests:rate1m
        eval_time: 1m
        exp_samples:
          - labels: 'job:app_requests:rate1m{job="app"}'
            value: 4

চালান:

promtool test rules rules.test.yml; echo "exit status: $?"
promtool test rules bad.test.yml; echo "exit status: $?"

টিউটোরিয়ালের run-এর output:

Processing test file: rules.test.yml
  SUCCESS

exit status: 0
Processing test file: bad.test.yml
  FAILED:
    expr: "job:app_requests:rate1m", time: 1m,
        exp: {__name__="job:app_requests:rate1m", job="app"} 4E+00
        got: {__name__="job:app_requests:rate1m", job="app"} 3E+00


exit status: 1
  • promtool test rules command rule-এর unit test চালায় Source 26সোর্স 26। একটা test file বিবেচনা করার rule file-এর তালিকা দেয় Source 16সোর্স 16।
  • প্রথম test group rule-গুলোতে দুটো counter ঢোকায়। 0+10x24 শুরু হয় 0 থেকে আর আরও ২৪টা sample-এ ১০ করে যোগ করে, আর 0+5x24 যোগ করে ৫। docs এটাকে পড়ে "series a থেকে শুরু হয়, তারপর আরও n-টা sample b করে বাড়ে" বলে Source 16সোর্স 16। ৫ সেকেন্ডে একটা sample ধরলে counter দুটো প্রতি সেকেন্ডে ২ আর ১ করে বাড়ে, তাই rate-দুটোর যোগফল ৩।
  • ১০ সেকেন্ডে exp_alerts: [] test আশা করে AppHighErrorRatio firing নয়। ১ মিনিটে সে আশা করে একটা alert, rule-এর label আর annotation সহ। group-টা এটাও দেখে যে ১ মিনিটে job:app_requests:rate1m ৩।
  • দ্বিতীয় group-এ শুধু ভালো counter আছে, আর সে কোনো alert আশা করে না। তৃতীয় group up-কে দেয় 1 1 1 0x20 মান, আর ১ মিনিটে AppDown আশা করে।
  • প্রথম file ছেপেছে SUCCESS আর শেষ হয়েছে exit status 0 দিয়ে। দ্বিতীয় file আশা করে ৪, আর আসল মান ৩। ব্যর্থতার output expression, সময়, প্রত্যাশিত sample (exp) আর rule যে sample দিয়েছে (got) দেখায়, আর exit status ছিল 1। ব্যর্থতার output আর exit status দুটো টিউটোরিয়ালের run থেকে।

৪. Alertmanager configuration লিখুন, আর server ছাড়াই routing test করুন। এটা alertmanager.yml নামে save করুন:

route:
  receiver: team-default
  group_by: [alertname]
  group_wait: 5s
  group_interval: 10s
  repeat_interval: 1h
  routes:
    - matchers:
        - severity="page"
      receiver: team-oncall

receivers:
  - name: team-default
  - name: team-oncall

চালান:

amtool check-config alertmanager.yml
amtool config routes show --config.file=alertmanager.yml
amtool config routes test --config.file=alertmanager.yml severity=page alertname=AppDown
amtool config routes test --config.file=alertmanager.yml severity=ticket alertname=AppHighErrorRatio

টিউটোরিয়ালের run-এর output:

Checking 'alertmanager.yml'  SUCCESS
Found:
 - global config
 - route
 - 0 inhibit rules
 - 2 receivers
 - 0 templates

Routing tree:
.
└── default-route  receiver: team-default
    └── {severity="page"}  receiver: team-oncall

team-oncall
team-default
  • root route alert পাঠায় team-default receiver-এ আর alertname ধরে সেগুলো group করে। একটা child route severity="page" alert পাঠায় team-oncall-এ। ফাইলের দুটো receiver-এ কোনো integration setting নেই। 5s, 10s আর 1h মান টিউটোরিয়ালের নিজের সিদ্ধান্ত। docs group_wait-কে বর্ণনা করে একটা নতুন group-এর প্রথম notification পাঠানোর আগে কতক্ষণ অপেক্ষা করতে হবে, সেটা হিসেবে Source 24সোর্স 24, আর repeat_interval-কে বর্ণনা করে শেষ notification আবার পাঠানোর আগে কতক্ষণ অপেক্ষা করতে হবে, সেটা হিসেবে Source 24সোর্স 24।
  • প্রতিটা alert routing tree-তে ঢোকে সবচেয়ে ওপরের route দিয়ে, তারপর child node-গুলো ঘুরে দেখে Source 24সোর্স 24।
  • amtool check-config ছেপেছে SUCCESS, আর গুনেছে route, ০টা inhibit rule, ২টা receiver আর ০টা template। তখনও কোনো Alertmanager server চালু ছিল না, কারণ ৫ নম্বর ধাপ সেটা চালু করে। configuration page UTF-8 strict mode-এর যাচাইয়ের জন্য amtool check-config দেখায় Source 24সোর্স 24। সে বলে, সেই যাচাইয়ের জন্য একটা চালু Alertmanager server লাগে না Source 24সোর্স 24।
  • amtool config routes show route-গুলোর tree ছেপেছে। amtool config routes test severity=page alert-এর জন্য ছেপেছে team-oncall, আর severity=ticket alert-এর জন্য team-default। Alertmanager-এর README বলে, amtool একটা configuration-এর route-গুলো text tree আকারে দেখাতে পারে Source 25সোর্স 25। সে আরও বলে, একটা alert-এর label set পাঠিয়ে আপনি routing test করতেও এটা ব্যবহার করতে পারেন Source 25সোর্স 25। README command দুটো লেখে amtool config routes Source 25সোর্স 25 আর amtool config routes test Source 25সোর্স 25 নামে। টিউটোরিয়াল প্রথমটা চালিয়েছে config routes show নামে, আর README সেটা ওভাবে লেখে না।

৫. server চালু করুন, আর Prometheus-কে প্রশ্ন করুন। চালান:

alertmanager --config.file=alertmanager.yml --storage.path=am-data --web.listen-address=127.0.0.1:19093 --cluster.listen-address= > am.out 2>&1 &
echo $! > am.pid
prometheus --config.file=prometheus.yml --storage.tsdb.path=prom-data --web.listen-address=127.0.0.1:19090 > prom.out 2>&1 &
echo $! > prom.pid
until curl -sf localhost:19090/-/ready; do sleep 1; done
sleep 12
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=up'; echo
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=sum by (code) (app_requests_total)'; echo
curl -s --get localhost:19090/api/v1/query --data-urlencode 'query=histogram_quantile(0.9, sum by (le) (app_request_duration_seconds_bucket))'; echo

টিউটোরিয়ালের run-এর output:

Prometheus Server is Ready.
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","instance":"127.0.0.1:18000","job":"app"},"value":[1795086690.402,"1"]}]}}
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"code":"200"},"value":[1795086690.416,"6"]},{"metric":{"code":"500"},"value":[1795086690.416,"2"]},{"metric":{"code":"404"},"value":[1795086690.416,"1"]}]}}
{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1795086690.431,"0.2749999999999999"]}]}}
  • --config.file flag হলো Prometheus configuration file-এর path Source 29সোর্স 29। --storage.tsdb.path flag হলো metric রাখার base path Source 29সোর্স 29। --web.listen-address flag হলো UI, API আর telemetry-র জন্য যে address-এ শুনতে হবে, সেটা Source 29সোর্স 29। data folder আর ১৯০৯০ ও ১৯০৯৩ port টিউটোরিয়ালের নিজের সিদ্ধান্ত।
  • --cluster.listen-address= দিলে Alertmanager আর আসা peer-অনুরোধ শোনে না Source 25সোর্স 25। টিউটোরিয়াল সেটা দিয়েছে। run-এর socket-তালিকায় কোনো gossip port নেই।
  • /-/ready ছেপেছে Prometheus Server is Ready. Prometheus traffic সামলাতে প্রস্তুত হলে ওই endpoint 200 ফেরত দেয় Source 28সোর্স 28। টিউটোরিয়ালের until loop তার জন্য অপেক্ষা করে।
  • API-র response format JSON Source 27সোর্স 27। /api/v1/query endpoint একটা এক মুহূর্তে একটা instant query মূল্যায়ন করে Source 27সোর্স 27।
  • up query একটা series ফেরত দিয়েছে, মান "1"। তার মানে instance সুস্থ ছিল, অর্থাৎ পৌঁছানো যাচ্ছিল Source 11সোর্স 11।
  • sum by (code) (app_requests_total) query code 200-এর জন্য ৬, 500-এর জন্য ২ আর 404-এর জন্য ১ ফেরত দিয়েছে। এগুলো ১ নম্বর ধাপের মোট: /-এ পাঁচটা আর /slow-এ একটা অনুরোধ মিলে ছয়টা 200।
  • histogram_quantile(0.9, sum by (le) (app_request_duration_seconds_bucket)) query ফেরত দিয়েছে 0.2749999999999999। নয়টা অনুরোধের আটটা ছিল ০.২৫ সেকেন্ড পর্যন্ত bucket-গুলোতে। docs বলে, φ-quantile হলো সেই পর্যবেক্ষণ-মান যার ক্রম N-টা পর্যবেক্ষণের মধ্যে φ*N-তম Source 20সোর্স 20। φ = ০.৯ আর N = ৯ হলে rank ৮.১, তাই টিউটোরিয়ালের নিজের হিসাবে উত্তরটা ০.২৫ থেকে ০.৫ পর্যন্ত bucket-এ, যেটায় নবম অনুরোধ আছে। quantile মান যে bucket-এ পড়ে, function তার ভেতরে interpolate করে Source 13সোর্স 13। classic histogram-এর জন্য সে ধরে নেয় bucket-এর ভেতরে পর্যবেক্ষণ সমানভাবে ছড়ানো Source 13সোর্স 13। তাতে হয় ০.২৫ আর ০.১ গুণ ০.২৫, অর্থাৎ ০.২৭৫।
  • টিউটোরিয়াল ওই query-তে rate() রাখেনি, তাই উত্তর app চালু হওয়ার পর থেকে নয়টা অনুরোধ জুড়ে। docs quantile হিসাবের সময়-জানালা ঠিক করতে rate() function ব্যবহার করে Source 13সোর্স 13। এটা টিউটোরিয়ালের নিজের সিদ্ধান্ত, যাতে সংখ্যাটা আবার পাওয়া যায়।

৬. alert firing করান, আর Alertmanager-এ দেখুন। ধাপটা কিছু সহায়ক function ঠিক করে, যা টিউটোরিয়াল লিখেছে। alerts প্রতিটা alert-এর নাম আর অবস্থা ছাপে /api/v1/alerts endpoint থেকে। wait_for একটা নির্দিষ্ট লাইন না আসা পর্যন্ত loop চালায়। পটভূমিতে একটা loop প্রতি একটা ভালো অনুরোধের সঙ্গে দুটো ব্যর্থ অনুরোধ পাঠায়। চালান:

alerts() { curl -s localhost:19090/api/v1/alerts | python3 -c 'import json, sys; [print(a["labels"]["alertname"], a["state"]) for a in json.load(sys.stdin)["data"]["alerts"]]'; }
wait_for() { until alerts | grep -q "$1"; do sleep 1; done; echo "--- Prometheus reports: $1"; alerts; }
AM="amtool --alertmanager.url=http://127.0.0.1:19093"

# traffic with two failing requests for every good one, in the background
( while true; do curl -s -o /dev/null localhost:18000/; curl -s -o /dev/null localhost:18000/fail; curl -s -o /dev/null localhost:18000/fail; sleep 1; done ) &
echo $! > traffic.pid
wait_for "AppHighErrorRatio pending"
wait_for "AppHighErrorRatio firing"
kill "$(cat traffic.pid)"
until $AM alert query | grep -q AppHighErrorRatio; do sleep 1; done
echo "--- Alertmanager received it:"; $AM alert query
$AM silence add alertname=AppHighErrorRatio --author=tutorial --comment="practice run" --duration=10m
echo "--- after the silence:"; $AM alert query; echo "(the line above ends the list of active alerts)"; $AM alert query --silenced

# stop the app: the scrape fails and up becomes 0
kill "$(cat app.pid)"
wait_for "AppDown pending"
wait_for "AppDown firing"
until $AM alert query | grep -q AppDown; do sleep 1; done
echo "--- Alertmanager received it:"; $AM alert query

টিউটোরিয়ালের run-এর output:

--- Prometheus reports: AppHighErrorRatio pending
AppHighErrorRatio pending
--- Prometheus reports: AppHighErrorRatio firing
AppHighErrorRatio firing
--- Alertmanager received it:
Alertname          Starts At                Summary                              State   
AppHighErrorRatio  2026-11-19 11:11:51 UTC  More than 20% of the requests fail.  active  
d009a065-d5f7-4960-9a46-5f79f358f22e
--- after the silence:
Alertname  Starts At  Summary  State  
(the line above ends the list of active alerts)
Alertname          Starts At                Summary                              State       
AppHighErrorRatio  2026-11-19 11:11:51 UTC  More than 20% of the requests fail.  suppressed  
--- Prometheus reports: AppDown pending
AppHighErrorRatio firing
AppDown pending
--- Prometheus reports: AppDown firing
AppHighErrorRatio firing
AppDown firing
--- Alertmanager received it:
Alertname  Starts At                Summary                               State   
AppDown    2026-11-19 11:12:11 UTC  The app does not answer its scrapes.  active  
  • /alerts endpoint সব সক্রিয় alert-এর তালিকা ফেরত দেয় Source 27সোর্স 27।
  • AppHighErrorRatio প্রথমে pending, পরে firing হিসেবে জানানো হয়েছে। একটা alert for-এর সময় ধরে ফেরত না আসা পর্যন্ত pending থাকে Source 14সোর্স 14। app যখন 500 দিচ্ছিল, তালিকায় এটাই ছিল একমাত্র alert।
  • amtool alert query alert-টা ছেপেছে active অবস্থায়। Starts At column UTC-তে। টিউটোরিয়ালের time zone ছিল +০৬, তাই alert-এর সময় machine-এর ঘড়ির ছয় ঘণ্টা পেছনে।
  • README দেখায় amtool silence add alertname=Test_Alert Source 25সোর্স 25। Alertmanager page বলে silence ঠিক করা হয় web interface-এ Source 23সোর্স 23। টিউটোরিয়াল তার বদলে amtool ব্যবহার করেছে, আর সে নতুন silence-এর ID ছেপেছে। তারপর amtool alert query কোনো সক্রিয় alert দেখায়নি, আর --silenced দিয়ে সে alert-টা দেখিয়েছে suppressed অবস্থায়। টিউটোরিয়াল যে page-গুলো পড়েছে, তার কোনোটাই --silenced flag বা suppressed অবস্থা বর্ণনা করে না।
  • app বন্ধ করার পর Prometheus AppDown-কে প্রথমে pending, পরে firing জানিয়েছে। তার up ছিল 0, কারণ scrape ব্যর্থ হয়েছিল Source 11সোর্স 11। AppHighErrorRatio তখনও firing ছিল, আর টিউটোরিয়াল সেটা কখন শেষ হয় তা দেখতে অপেক্ষা করেনি।
  • Alertmanager AppDown-কে active দেখিয়েছে। অন্য alert-টা silence করা ছিল, তাই সেটা তালিকায় ছিল না।

৭. Loki চালু করুন, app-এর log লাইন তাতে পাঠান, আর query করুন। Loki configuration এসেছে docs থেকে। page-টা filesystem-ভিত্তিক Loki deploy করার একটা সম্পূর্ণ configuration তালিকাভুক্ত করে Source 37সোর্স 37। টিউটোরিয়াল port বদলেছে, আর folder বদলেছে, যা এখানে loki-data, আর page-এ /tmp/loki Source 37সোর্স 37। সে HTTP listen address-ও ঠিক করেছে, আর reporting_enabled: false দিয়ে analytics যোগ করেছে। configuration reference সেই setting-কে বর্ণনা করে "Enable anonymous usage reporting" বলে Source 38সোর্স 38। এটা loki.yml নামে save করুন:

auth_enabled: false

server:
  http_listen_address: 127.0.0.1
  http_listen_port: 13100
  grpc_listen_port: 19096

common:
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory
  replication_factor: 1
  path_prefix: loki-data

schema_config:
  configs:
    - from: 2020-05-15
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

storage_config:
  filesystem:
    directory: loki-data/chunks

analytics:
  reporting_enabled: false

push.py sender টিউটোরিয়ালের নিজের। সে app.log-এর লাইনগুলো পড়ে, আর job="app" label-সহ একটা stream হিসেবে পাঠায়:

"""Send the lines of an app log to Loki, as one stream with the label job="app".

  python3 push.py app.log http://127.0.0.1:13100
Each line starts with ts=<UTC time with milliseconds>. That time becomes the timestamp of the entry in Loki.
"""
import datetime
import json
import re
import sys
import urllib.request

path, base = sys.argv[1], sys.argv[2]
values = []
for line in open(path, encoding="utf-8").read().splitlines():
    stamp = re.match(r"ts=(\S+)", line).group(1)
    when = datetime.datetime.fromisoformat(stamp)
    values.append([str(int(when.timestamp() * 1000) * 1_000_000), line])
body = json.dumps({"streams": [{"stream": {"job": "app"}, "values": values}]}).encode()
request = urllib.request.Request(base + "/loki/api/v1/push", data=body, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request) as response:
    print(f"pushed {len(values)} lines, HTTP status {response.status}")

চালান:

loki -config.file=loki.yml > loki.out 2>&1 &
echo $! > loki.pid
until [ "$(curl -s -o /dev/null -w '%{http_code}' localhost:13100/ready)" = 200 ]; do sleep 2; done
curl -s localhost:13100/ready
python3 push.py app.log http://127.0.0.1:13100
# a helper that prints the result and leaves out the "stats" field of the response
lq() { curl -s --get "localhost:13100/loki/api/v1/$1" --data-urlencode "query=$2" "${@:3}" | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["status"], d["data"]["resultType"]); print(json.dumps(d["data"]["result"]))'; }
curl -s localhost:13100/loki/api/v1/labels; echo
lq query_range '{job="app"} |= "code=500"' --data-urlencode limit=2
lq query 'sum by (path) (count_over_time({job="app"} | logfmt | code >= 500 [1h]))'

টিউটোরিয়ালের run-এর output:

ready
pushed 69 lines, HTTP status 204
{"status":"success","data":["job","service_name"]}

success streams
[{"stream": {"detected_level": "error", "job": "app", "service_name": "app"}, "values": [["1795086711780000000", "ts=2026-11-19T11:11:51.780Z level=error path=/fail code=500 duration_ms=1"], ["1795086711754000000", "ts=2026-11-19T11:11:51.754Z level=error path=/fail code=500 duration_ms=0"]]}]
success vector
[{"metric": {"path": "/fail"}, "value": [1795086751.347, "42"]}]
  • /ready ছেপেছে ready। Loki instance traffic নিতে প্রস্তুত হলে ওই endpoint HTTP 200 ফেরত দেয় Source 36সোর্স 36। টিউটোরিয়ালের loop 200 status-এর জন্য অপেক্ষা করে।
  • push.py 69টা লাইন পাঠিয়েছে, আর endpoint 204 status দিয়ে সাড়া দিয়েছে। প্রতিটা entry-র timestamp একটা string, API যেমন চায় Source 36সোর্স 36।
  • labels endpoint ফেরত দিয়েছে job আর service_name। টিউটোরিয়াল শুধু job পাঠিয়েছে। Loki নিজে service_name যোগ করেছে, মান app, যা job-এর মান। stream-এ service_name না থাকলে Loki একটা label-তালিকা থেকে ক্রমানুসারে প্রথম ফাঁকা-নয় এমন মান খোঁজে Source 32সোর্স 32।
  • প্রথম ফলের stream-এ detected_level label-ও আছে, মান error। configuration reference বলে, Loki ingestion-এর সময় log level খুঁজে নিয়ে যোগ করতে পারে, যদি আগে থেকে না থাকে Source 38সোর্স 38। টিউটোরিয়াল এটা সেট করেনি, আর টিউটোরিয়াল যে page-গুলো পড়েছে, তার কোনোটাই detected_level key-র নাম বলে না।
  • {job="app"} |= "code=500" log query stream বেছে নেয়, আর code=500 আছে এমন লাইন রাখে। একটা line filter expression মিলে যাওয়া log stream-এর ওপর একটা distributed grep চালায়, আর যে লাইন মেলে না তা বাদ দেয় Source 34সোর্স 34। limit=2 দুটো entry রেখেছে। limit parameter হলো ফেরত দেওয়ার entry-র সর্বোচ্চ সংখ্যা, আর তার default 100 Source 36সোর্স 36।
  • sum by (path) (count_over_time({job="app"} | logfmt | code >= 500 [1h])) metric query একটা series ফেরত দিয়েছে, path="/fail", মান 42। count_over_time function দেওয়া পরিসরের মধ্যে প্রতিটা log stream-এর entry গোনে Source 35সোর্স 35। logfmt stage প্রতিটা log লাইন parse করে আরও label বের করে, আর পরের stage সেগুলো দিয়ে ছেঁকে নেয় Source 34সোর্স 34। log file-এ /fail-এর 42টা লাইন ছিল, তাই দুটো সংখ্যা মেলে। সংখ্যাটা প্রতিটা run-এ আলাদা, কারণ ৬ নম্বর ধাপের loop কতগুলো অনুরোধ পাঠিয়েছে তার ওপর তা নির্ভর করে।
  • lq সহায়ক response-এর stats field বাদ দেয়। query endpoint query চালানোর একটা পরিসংখ্যান-সেট ফেরত দেয় Source 36সোর্স 36।

৮. এক service থেকে আরেক service-এ trace context পাঠান। script-এ একটা process-এ দুটো service আছে, service-a আর service-b। headers dictionary তাদের মধ্যের HTTP অনুরোধের জায়গা নেয়, তাই কোনো network ব্যবহার হয় না। script SDK-র ConsoleSpanExporter ব্যবহার করে, যা opentelemetry-sdk package-এর সঙ্গেই আসে Source 5সোর্স 5। সে context হাতে করে পাঠায়, Python docs যেমন দেখায় Source 4সোর্স 4। একই page বলে context propagate করতে instrumentation library ব্যবহার করতে Source 4সোর্স 4। one_line function আর পাঁচটা check টিউটোরিয়ালের নিজের। script otel_demo.py নামে save করুন:

"""Trace context propagation with the OpenTelemetry Python SDK: two "services" in one process.

The dictionary `headers` stands in for the HTTP request between them. Each span is printed on one line when it ends.
"""
import json
import re

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

SPANS = []


def one_line(span):
    d = json.loads(span.to_json())
    row = {"name": d["name"], "trace_id": d["context"]["trace_id"], "span_id": d["context"]["span_id"], "parent_id": d["parent_id"]}
    SPANS.append(row)
    return json.dumps(row) + "\n"


provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("practice")
propagator = TraceContextTextMapPropagator()


def service_b(headers):
    context = propagator.extract(carrier=headers)
    with tracer.start_as_current_span("service-b handles the request", context=context):
        pass


print("case 1: service A sends the traceparent header")
with tracer.start_as_current_span("service-a calls service-b"):
    headers = {}
    propagator.inject(headers)
    print("traceparent:", headers["traceparent"])
    service_b(headers)

print("case 2: the header is lost on the way")
with tracer.start_as_current_span("service-a calls service-b, no header"):
    service_b({})

b1, a1, b2, a2 = SPANS  # a span is printed when it ends, so each service-b span comes before its service-a span
print("check 1: header has the form 00-<32 hex>-<16 hex>-<2 hex>:", bool(re.fullmatch(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", headers["traceparent"])))
print("check 2: case 1, both spans share one trace id:", a1["trace_id"] == b1["trace_id"])
print("check 3: case 1, the parent of the service-b span is the service-a span:", b1["parent_id"] == a1["span_id"])
print("check 4: case 2, the trace ids differ:", a2["trace_id"] != b2["trace_id"])
print("check 5: case 2, the service-b span has no parent:", b2["parent_id"] is None)

চালান:

venv/bin/python otel_demo.py

টিউটোরিয়ালের run-এর output:

case 1: service A sends the traceparent header
traceparent: 00-0476e04404089b682e7a22e120886d1e-d4f79e01e18511ac-03
{"name": "service-b handles the request", "trace_id": "0x0476e04404089b682e7a22e120886d1e", "span_id": "0x60a1a9c5df67ed51", "parent_id": "0xd4f79e01e18511ac"}
{"name": "service-a calls service-b", "trace_id": "0x0476e04404089b682e7a22e120886d1e", "span_id": "0xd4f79e01e18511ac", "parent_id": null}
case 2: the header is lost on the way
{"name": "service-b handles the request", "trace_id": "0x20c17ac1fac019492a3ea81ed585d55e", "span_id": "0xf955daacc6d0807c", "parent_id": null}
{"name": "service-a calls service-b, no header", "trace_id": "0x180f73c286f70edb200fa915c2cd2174", "span_id": "0x95f1c3f4063851ef", "parent_id": null}
check 1: header has the form 00-<32 hex>-<16 hex>-<2 hex>: True
check 2: case 1, both spans share one trace id: True
check 3: case 1, the parent of the service-b span is the service-a span: True
check 4: case 2, the trace ids differ: True
check 5: case 2, the service-b span has no parent: True
  • case 1-এ service A headers-এ context রেখেছে। header-এ চারটা field আছে Source 6সোর্স 6। তার শেষ field ছিল 03। flags-এর সবচেয়ে ডানের bit সেট থাকলে বোঝায় caller trace data রেকর্ড করে থাকতে পারে Source 6সোর্স 6। page আরও বলে, flags একটা bit field, আর আপনি সেটা সংখ্যা হিসেবে পড়তে পারেন না Source 6সোর্স 6। তাই 03 বোঝায় সবচেয়ে ডানের bit সেট, আর আরও একটা bit সেট। টিউটোরিয়াল যে page-গুলো পড়েছে, তার কোনোটাই সেই অন্য bit-এর নাম বলে না।
  • case 1-এর দুটো span-এর trace_id এক। service B-র span-এর parent_id হলো service A-র span-এর span_id। service A-র span-এর trace_id আছে কিন্তু parent_id নেই, আর তা দেখেই বোঝা যায় যে সেটা একটা root span Source 41সোর্স 41।
  • case 2-এ header হারিয়ে গেছে, আর service B একটা নতুন trace শুরু করেছে: তার trace_id আলাদা, আর তার কোনো parent নেই। W3C page বলে, কোনো traceparent header না এলে vendor একটা নতুন trace-id আর parent-id বানায়, যা বর্তমান অনুরোধ বোঝায় Source 6সোর্স 6। case 2-এর service-A span-এর একটা তৃতীয় trace id আছে, কারণ সেটাও একটা নতুন root span।
  • script-এর পাঁচটা check ছেপেছে True। case 2 দেখায় ভাঙা propagation কেমন দেখায়: একটা trace আশা করা জায়গায় আলাদা id-র দুটো trace।

How a tester uses it

  • Read what the app counts, and compare it with what you sent. In step 1, the tutorial sent nine requests and read the counters from /metrics. In step 5, Prometheus returned the same totals by status code. A counter can only increase or be reset to zero on restart Source 10সোর্স 10.
  • Use up to see whether the scrape works. The value is 1 if the instance is healthy, that is, reachable, or 0 if the scrape failed Source 11সোর্স 11. While the app answered 500 to /fail, only AppHighErrorRatio was reported. AppDown appeared only after the app was stopped. The SRE book counts an HTTP 200 with the wrong content as an error too, implicitly Source 7সোর্স 7.
  • Unit-test the alert rules without a server. In step 3, promtool test rules ran three test groups against the rules and ended with the exit status 0. The wrong expectation ended with the exit status 1, and the output showed exp and got. A test can also expect that an alert does not fire, with an empty exp_alerts Source 16সোর্স 16.
  • Test the routing of the alerts. In step 4, amtool config routes test returned the receiver for a given set of labels, and it needed no server. Every alert enters the routing tree at the top-level route and then traverses the child nodes Source 24সোর্স 24.
  • Wait for the state that you expect. In step 6, the alert was pending first, and firing later, because of its for time Source 14সোর্স 14. The helper wait_for of the tutorial polls the endpoint /api/v1/alerts until the line that it wants shows Source 27সোর্স 27.
  • Look at the labels of the series. The tutorial's app counts a path that does not exist under other. The docs say not to use labels to store dimensions with high cardinality, such as user IDs Source 18সোর্স 18. For Loki, too many label value combinations leads to too many streams Source 33সোর্স 33.
  • Search the logs by label and by content. In step 7, the label job="app" selected the stream and a line filter kept the lines with code=500 Source 34সোর্স 34. A metric query counted the failing lines, and the number agreed with the log file.
  • Check that a trace survives a hop. In step 8, the two spans shared one trace id when the header was passed, and had different ids when it was lost. With context propagation, signals can be correlated with each other, regardless of where they are generated Source 3সোর্স 3.

সহজ English

  • Read what the app counts, and compare it with what you sent. In step 1, the tutorial sent nine requests and read the counters from /metrics. In step 5, Prometheus returned the same totals by status code. A counter can only increase or be reset to zero on restart Source 10সোর্স 10.
  • Use up to see whether the scrape works. The value is 1 if the instance is healthy, that is, reachable, or 0 if the scrape failed Source 11সোর্স 11. While the app answered 500 to /fail, only AppHighErrorRatio was reported. AppDown appeared only after the app was stopped. The SRE book counts an HTTP 200 with the wrong content as an error too, implicitly Source 7সোর্স 7.
  • Unit-test the alert rules without a server. In step 3, promtool test rules ran three test groups against the rules and ended with the exit status 0. The wrong expectation ended with the exit status 1, and the output showed exp and got. A test can also expect that an alert does not fire, with an empty exp_alerts Source 16সোর্স 16.
  • Test the routing of the alerts. In step 4, amtool config routes test returned the receiver for a given set of labels, and it needed no server. Every alert enters the routing tree at the top-level route and then traverses the child nodes Source 24সোর্স 24.
  • Wait for the state that you expect. In step 6, the alert was pending first, and firing later, because of its for time Source 14সোর্স 14. The helper wait_for of the tutorial polls the endpoint /api/v1/alerts until the line that it wants shows Source 27সোর্স 27.
  • Look at the labels of the series. The tutorial's app counts a path that does not exist under other. The docs say not to use labels to store dimensions with high cardinality, such as user IDs Source 18সোর্স 18. For Loki, too many label value combinations leads to too many streams Source 33সোর্স 33.
  • Search the logs by label and by content. In step 7, the label job="app" selected the stream and a line filter kept the lines with code=500 Source 34সোর্স 34. A metric query counted the failing lines, and the number agreed with the log file.
  • Check that a trace survives a hop. In step 8, the two spans shared one trace id when the header was passed, and had different ids when it was lost. With context propagation, signals can be correlated with each other, regardless of where they are generated Source 3সোর্স 3.

বাংলা ব্যাখ্যা

  • app যা গোনে তা পড়ুন, আর আপনি যা পাঠিয়েছেন তার সঙ্গে মেলান। ১ নম্বর ধাপে টিউটোরিয়াল নয়টা অনুরোধ পাঠিয়ে /metrics থেকে counter পড়েছে। ৫ নম্বর ধাপে Prometheus status code ধরে একই মোট ফেরত দিয়েছে। একটা counter শুধু বাড়তে পারে বা restart-এ শূন্যে ফিরতে পারে Source 10সোর্স 10।
  • scrape চলছে কি না দেখতে up ব্যবহার করুন। instance সুস্থ, অর্থাৎ পৌঁছানো যায়, হলে মান 1, আর scrape ব্যর্থ হলে 0 Source 11সোর্স 11। app যখন /fail-এ 500 দিচ্ছিল, তখন শুধু AppHighErrorRatio জানানো হয়েছে। AppDown এসেছে app বন্ধ করার পরেই। SRE book ভুল বিষয়বস্তুসহ HTTP 200-কেও অপ্রকাশ্য error ধরে Source 7সোর্স 7।
  • server ছাড়াই alert rule-এর unit test করুন। ৩ নম্বর ধাপে promtool test rules rule-গুলোর বিপরীতে তিনটা test group চালিয়েছে আর exit status 0 দিয়ে শেষ হয়েছে। ভুল প্রত্যাশা শেষ হয়েছে exit status 1 দিয়ে, আর output exp আর got দেখিয়েছে। একটা test এটাও আশা করতে পারে যে একটা alert firing হবে না, exp_alerts ফাঁকা রেখে Source 16সোর্স 16।
  • alert-এর routing test করুন। ৪ নম্বর ধাপে amtool config routes test কিছু label-এর জন্য receiver ফেরত দিয়েছে, আর তার server লাগেনি। প্রতিটা alert routing tree-তে ঢোকে সবচেয়ে ওপরের route দিয়ে, তারপর child node-গুলো ঘুরে দেখে Source 24সোর্স 24।
  • আপনি যে অবস্থা আশা করেন তার জন্য অপেক্ষা করুন। ৬ নম্বর ধাপে alert প্রথমে pending, পরে firing ছিল, তার for সময়ের কারণে Source 14সোর্স 14। টিউটোরিয়ালের wait_for সহায়ক /api/v1/alerts endpoint-কে poll করে, যতক্ষণ না তার চাওয়া লাইন আসে Source 27সোর্স 27।
  • series-এর label দেখুন। টিউটোরিয়ালের app এমন path-কে, যা নেই, other-এর নিচে গোনে। docs বলে, user ID-র মতো high cardinality-র dimension রাখতে label ব্যবহার করবেন না Source 18সোর্স 18। Loki-র ক্ষেত্রে label-মানের অনেক বেশি সমন্বয় মানে অনেক বেশি stream Source 33সোর্স 33।
  • label আর বিষয়বস্তু ধরে log খুঁজুন। ৭ নম্বর ধাপে job="app" label stream বেছেছে, আর একটা line filter code=500 আছে এমন লাইন রেখেছে Source 34সোর্স 34। একটা metric query ব্যর্থ লাইন গুনেছে, আর সংখ্যাটা log file-এর সঙ্গে মিলেছে।
  • একটা trace এক hop টিকে থাকে কি না দেখুন। ৮ নম্বর ধাপে header পাঠানো হলে দুটো span-এর trace id এক ছিল, আর হারালে আলাদা। context propagation থাকলে signal একে অপরের সঙ্গে মেলানো যায়, সেগুলো যেখানেই তৈরি হোক Source 3সোর্স 3।

Common mistakes

  • Using rate() on a gauge. The rate function should only be used with counters Source 13সোর্স 13. Applied to gauge floats, it will most likely produce a nonsensical result, but the query will be processed without complaints Source 12সোর্স 12.
  • Aggregating before rate(). When you combine rate() with an aggregation operator such as sum(), always take a rate() first, then aggregate Source 13সোর্স 13. Otherwise rate() cannot detect counter resets when your target restarts Source 13সোর্স 13. The recording rule of step 2 takes the rate() first.
  • Using a counter for a value that can decrease. Do not use a counter to expose a value that can decrease Source 10সোর্স 10. The docs give an example: do not use a counter for the number of currently running processes, and use a gauge instead Source 10সোর্স 10.
  • Aggregating the quantiles of a summary. The page on histograms says that Prometheus implements pre-calculated quantiles as a metric type called summary Source 20সোর্স 20. It adds that you cannot recalculate the quantiles later for another time window or another percentile, and that you cannot aggregate quantiles Source 20সোর্স 20.
  • Putting unbounded values in labels. Do not use labels to store dimensions with high cardinality, such as user IDs, email addresses, or other unbounded sets of values Source 18সোর্স 18. In Loki, the penalties of too many streams are a large index and small chunks in the store Source 33সোর্স 33.
  • Reading pending as firing. Alerts which have not yet fired for long enough are considered pending Source 14সোর্স 14. In step 6, AppHighErrorRatio was pending first.
  • Thinking that a silence resolves an alert. If an alert matches an active silence, no notifications will be sent out for that alert Source 23সোর্স 23. In step 6, Prometheus still reported the silenced alert as firing.
  • Reading up as the health of the application. The value of up says whether the scrape worked Source 11সোর্স 11. In step 6, the alert on the error ratio fired while AppDown did not.
  • Counting only the explicit errors. The SRE book counts an HTTP 200 success response, coupled with the wrong content, as an error, implicitly Source 7সোর্স 7. The rule AppHighErrorRatio counts only the status codes from 500 to 599, so it would not see such a response.
  • Mixing the latency of successes and failures. It is important to distinguish between the latency of successful requests and the latency of failed requests Source 7সোর্স 7. The histogram of the tutorial's app has no label for the status code, so it mixes them.
  • Trusting only a green promtool check. The command promtool check rules checks if the rule files are valid or not, and promtool test rules runs unit tests for rules Source 26সোর্স 26. They are two commands for two jobs.
  • Forgetting a series that does not exist yet. Time series that are not present until something happens are difficult to deal with Source 19সোর্স 19. The docs say to export a default value such as 0 for any time series that you know may exist in advance Source 19সোর্স 19.
  • Sending a timestamp to Loki as a number. The push endpoint needs the timestamp as a string, and it returns a 400 error otherwise Source 36সোর্স 36.
  • Expecting a line filter to ignore case. The line filter expression discards the lines that do not match the case-sensitive expression Source 34সোর্স 34.
  • Losing the trace header on a hop. When no traceparent header is received, the vendor creates a new trace-id and parent-id that represents the current request Source 6সোর্স 6. Case 2 of step 8 shows two traces where one was expected.
  • Reading the trace flags as a number. The flags are a bit field, and you cannot interpret them by decoding the hex value and looking at the resulting number Source 6সোর্স 6. The value in step 8 was 03.
  • Leaving a port open to the network. In the tutorial's run, the gRPC port of Loki listened on all addresses. Run step 7 on a machine and a network that you trust.

সহজ English

  • Using rate() on a gauge. The rate function should only be used with counters Source 13সোর্স 13. Applied to gauge floats, it will most likely produce a nonsensical result, but the query will be processed without complaints Source 12সোর্স 12.
  • Aggregating before rate(). When you combine rate() with an aggregation operator such as sum(), always take a rate() first, then aggregate Source 13সোর্স 13. Otherwise rate() cannot detect counter resets when your target restarts Source 13সোর্স 13. The recording rule of step 2 takes the rate() first.
  • Using a counter for a value that can decrease. Do not use a counter to expose a value that can decrease Source 10সোর্স 10. The docs give an example: do not use a counter for the number of currently running processes, and use a gauge instead Source 10সোর্স 10.
  • Aggregating the quantiles of a summary. The page on histograms says that Prometheus implements pre-calculated quantiles as a metric type called summary Source 20সোর্স 20. It adds that you cannot recalculate the quantiles later for another time window or another percentile, and that you cannot aggregate quantiles Source 20সোর্স 20.
  • Putting unbounded values in labels. Do not use labels to store dimensions with high cardinality, such as user IDs, email addresses, or other unbounded sets of values Source 18সোর্স 18. In Loki, the penalties of too many streams are a large index and small chunks in the store Source 33সোর্স 33.
  • Reading pending as firing. Alerts which have not yet fired for long enough are considered pending Source 14সোর্স 14. In step 6, AppHighErrorRatio was pending first.
  • Thinking that a silence resolves an alert. If an alert matches an active silence, no notifications will be sent out for that alert Source 23সোর্স 23. In step 6, Prometheus still reported the silenced alert as firing.
  • Reading up as the health of the application. The value of up says whether the scrape worked Source 11সোর্স 11. In step 6, the alert on the error ratio fired while AppDown did not.
  • Counting only the explicit errors. The SRE book counts an HTTP 200 success response, coupled with the wrong content, as an error, implicitly Source 7সোর্স 7. The rule AppHighErrorRatio counts only the status codes from 500 to 599, so it would not see such a response.
  • Mixing the latency of successes and failures. It is important to distinguish between the latency of successful requests and the latency of failed requests Source 7সোর্স 7. The histogram of the tutorial's app has no label for the status code, so it mixes them.
  • Trusting only a green promtool check. The command promtool check rules checks if the rule files are valid or not, and promtool test rules runs unit tests for rules Source 26সোর্স 26. They are two commands for two jobs.
  • Forgetting a series that does not exist yet. Time series that are not present until something happens are difficult to deal with Source 19সোর্স 19. The docs say to export a default value such as 0 for any time series that you know may exist in advance Source 19সোর্স 19.
  • Sending a timestamp to Loki as a number. The push endpoint needs the timestamp as a string, and it returns a 400 error otherwise Source 36সোর্স 36.
  • Expecting a line filter to ignore case. The line filter expression discards the lines that do not match the case-sensitive expression Source 34সোর্স 34.
  • Losing the trace header on a hop. When no traceparent header is received, the vendor creates a new trace-id and parent-id that represents the current request Source 6সোর্স 6. Case 2 of step 8 shows two traces where one was expected.
  • Reading the trace flags as a number. The flags are a bit field, and you cannot interpret them by decoding the hex value and looking at the resulting number Source 6সোর্স 6. The value in step 8 was 03.
  • Leaving a port open to the network. In the tutorial's run, the gRPC port of Loki listened on all addresses. Run step 7 on a machine and a network that you trust.

বাংলা ব্যাখ্যা

  • gauge-এ rate() ব্যবহার করা। rate function শুধু counter-এর সঙ্গে ব্যবহার করা উচিত Source 13সোর্স 13। gauge float-এ প্রয়োগ করলে খুব সম্ভব অর্থহীন ফল আসবে, কিন্তু query কোনো অভিযোগ ছাড়াই চলবে Source 12সোর্স 12।
  • rate()-এর আগে aggregate করা। rate()-কে sum()-এর মতো কোনো aggregation operator-এর সঙ্গে মেলালে সবসময় আগে rate() নিন, তারপর aggregate করুন Source 13সোর্স 13। নইলে target restart হলে rate() counter reset ধরতে পারে না Source 13সোর্স 13। ২ নম্বর ধাপের recording rule আগে rate() নেয়।
  • যে মান কমতে পারে তার জন্য counter ব্যবহার করা। যে মান কমতে পারে তা দেখাতে counter ব্যবহার করবেন না Source 10সোর্স 10। docs একটা উদাহরণ দেয়: এখন চলছে এমন process-এর সংখ্যার জন্য counter ব্যবহার করবেন না, বদলে gauge ব্যবহার করুন Source 10সোর্স 10।
  • summary-র quantile aggregate করা। histogram-সংক্রান্ত page বলে, Prometheus আগে-হিসাব-করা quantile প্রয়োগ করে summary নামের একটা metric type হিসেবে Source 20সোর্স 20। সে আরও বলে, আপনি অন্য সময়-জানালা বা অন্য percentile-এর জন্য পরে quantile আবার হিসাব করতে পারবেন না, আর quantile aggregate করতে পারবেন না Source 20সোর্স 20।
  • label-এ সীমাহীন মান রাখা। user ID, email address বা অন্য সীমাহীন মানের মতো high cardinality-র dimension রাখতে label ব্যবহার করবেন না Source 18সোর্স 18। Loki-তে অনেক বেশি stream-এর শাস্তি হলো একটা বড় index আর store-এ ছোট chunk Source 33সোর্স 33।
  • pending-কে firing পড়া। যে alert এখনও যথেষ্ট সময় ধরে ফেরত আসেনি, সেগুলো pending ধরা হয় Source 14সোর্স 14। ৬ নম্বর ধাপে AppHighErrorRatio প্রথমে pending ছিল।
  • ভাবা যে silence একটা alert মিটিয়ে দেয়। একটা alert সক্রিয় silence-এর সঙ্গে মিললে সেই alert-এর জন্য কোনো notification পাঠানো হবে না Source 23সোর্স 23। ৬ নম্বর ধাপে Prometheus তখনও silence করা alert-টাকে firing জানিয়েছে।
  • up-কে application-এর সুস্থতা পড়া। up-এর মান বলে scrape কাজ করেছে কি না Source 11সোর্স 11। ৬ নম্বর ধাপে error ratio-র alert firing হয়েছে, কিন্তু AppDown হয়নি।
  • শুধু প্রকাশ্য error গোনা। SRE book ভুল বিষয়বস্তুসহ একটা HTTP 200 সাফল্যের response-কেও অপ্রকাশ্য error ধরে Source 7সোর্স 7। AppHighErrorRatio rule শুধু 500 থেকে 599 status code গোনে, তাই সে এমন response দেখবে না।
  • সফল আর ব্যর্থ অনুরোধের latency মিশিয়ে ফেলা। সফল অনুরোধের latency আর ব্যর্থ অনুরোধের latency আলাদা করে দেখা গুরুত্বপূর্ণ Source 7সোর্স 7। টিউটোরিয়ালের app-এর histogram-এ status code-এর label নেই, তাই সে দুটোকে মিশিয়ে ফেলে।
  • শুধু সবুজ promtool check-এর ওপর ভরসা করা। promtool check rules command দেখে rule file বৈধ কি না, আর promtool test rules rule-এর unit test চালায় Source 26সোর্স 26। দুটো কাজের জন্য দুটো command।
  • এখনও নেই এমন series ভুলে যাওয়া। যে time series কিছু ঘটার আগে থাকে না, তা সামলানো কঠিন Source 19সোর্স 19। docs বলে, যে time series আগে থেকেই থাকতে পারে বলে আপনি জানেন, তার জন্য 0-র মতো একটা default মান export করতে Source 19সোর্স 19।
  • Loki-তে timestamp সংখ্যা হিসেবে পাঠানো। push endpoint-এর timestamp string হিসেবে লাগে, নইলে সে 400 error ফেরত দেয় Source 36সোর্স 36।
  • line filter case উপেক্ষা করবে বলে ধরে নেওয়া। line filter expression case-sensitive expression-এর সঙ্গে না মেলা লাইন বাদ দেয় Source 34সোর্স 34।
  • এক hop-এ trace header হারানো। কোনো traceparent header না এলে vendor একটা নতুন trace-id আর parent-id বানায়, যা বর্তমান অনুরোধ বোঝায় Source 6সোর্স 6। ৮ নম্বর ধাপের case 2 একটা trace আশা করা জায়গায় দুটো trace দেখায়।
  • trace flags-কে সংখ্যা হিসেবে পড়া। flags একটা bit field, আর আপনি hex মান decode করে ফলের সংখ্যা দেখে সেগুলো বুঝতে পারেন না Source 6সোর্স 6। ৮ নম্বর ধাপে মান ছিল 03।
  • network-এর জন্য একটা port খোলা রাখা। টিউটোরিয়ালের run-এ Loki-র gRPC port সব address-এ শুনেছে। ৭ নম্বর ধাপ এমন machine আর network-এ চালান, যাকে আপনি বিশ্বাস করেন।

What a tester can check

Tutorial advice

This list is the tutorial's own advice for a tester who works with monitoring and observability tools.

  • Run promtool check config, promtool check rules, and promtool test rules on every change to the rule files, and fail the build on a non-zero exit status.
  • Write two unit tests for each alert: one that must fire, and one that must not fire, with an empty exp_alerts.
  • Test the routing with amtool config routes test for each severity and each receiver that matters.
  • After a test run, read the counters and compare the difference with what the test sent, not the value.
  • Look at up for every target before you trust a graph.
  • Wait for the state that you expect, pending or firing, with a poll and a time limit.
  • Look at the labels of every new metric, and refuse ids, user input, and other unbounded values.
  • Count the failures in two places, the metric and the log, and compare the two numbers.
  • Look at the latency of the failed requests and the latency of the successful requests apart.
  • For one request, look for the same trace id in every service, and test one case where the header is lost.
  • Keep secrets, personal data, and tokens out of logs, labels, and span attributes.
  • Run a local Loki or Prometheus on a machine and a network that you trust, and look at which ports it opens.
  • Record the date, the versions, and the exact commands with each result.

সহজ English

Tutorial advice

This list is the tutorial's own advice for a tester who works with monitoring and observability tools.

  • Run promtool check config, promtool check rules, and promtool test rules on every change to the rule files, and fail the build on a non-zero exit status.
  • Write two unit tests for each alert: one that must fire, and one that must not fire, with an empty exp_alerts.
  • Test the routing with amtool config routes test for each severity and each receiver that matters.
  • After a test run, read the counters and compare the difference with what the test sent, not the value.
  • Look at up for every target before you trust a graph.
  • Wait for the state that you expect, pending or firing, with a poll and a time limit.
  • Look at the labels of every new metric, and refuse ids, user input, and other unbounded values.
  • Count the failures in two places, the metric and the log, and compare the two numbers.
  • Look at the latency of the failed requests and the latency of the successful requests apart.
  • For one request, look for the same trace id in every service, and test one case where the header is lost.
  • Keep secrets, personal data, and tokens out of logs, labels, and span attributes.
  • Run a local Loki or Prometheus on a machine and a network that you trust, and look at which ports it opens.
  • Record the date, the versions, and the exact commands with each result.

বাংলা ব্যাখ্যা

Tutorial advice

এই তালিকা টিউটোরিয়ালের নিজের পরামর্শ, এমন একজন tester-এর জন্য যিনি monitoring আর observability tool নিয়ে কাজ করেন।

  • rule file বদলালেই promtool check config, promtool check rules আর promtool test rules চালান, আর শূন্য নয় এমন exit status হলে build ব্যর্থ করুন।
  • প্রতিটা alert-এর জন্য দুটো unit test লিখুন: একটা যেটা firing হতেই হবে, আর একটা যেটা firing হবে না, ফাঁকা exp_alerts দিয়ে।
  • প্রতিটা severity আর প্রতিটা গুরুত্বপূর্ণ receiver-এর জন্য amtool config routes test দিয়ে routing test করুন।
  • একটা test run-এর পর counter পড়ুন, আর test যা পাঠিয়েছে তার সঙ্গে পার্থক্য মেলান, মান নয়।
  • একটা graph-এ ভরসা করার আগে প্রতিটা target-এর up দেখুন।
  • আপনি যে অবস্থা আশা করেন, pending বা firing, তার জন্য poll আর সময়সীমা দিয়ে অপেক্ষা করুন।
  • প্রতিটা নতুন metric-এর label দেখুন, আর id, user input আর অন্য সীমাহীন মান প্রত্যাখ্যান করুন।
  • ব্যর্থতা দুই জায়গায় গুনুন, metric আর log, আর দুটো সংখ্যা মেলান।
  • ব্যর্থ অনুরোধের latency আর সফল অনুরোধের latency আলাদা করে দেখুন।
  • একটা অনুরোধের জন্য প্রতিটা service-এ একই trace id খুঁজুন, আর header হারানোর একটা case test করুন।
  • secret, ব্যক্তিগত data আর token log, label আর span attribute-এর বাইরে রাখুন।
  • স্থানীয় Loki বা Prometheus এমন machine আর network-এ চালান, যাকে আপনি বিশ্বাস করেন, আর দেখুন সে কোন port খোলে।
  • প্রতিটা ফলের সঙ্গে তারিখ, version আর হুবহু command রাখুন।

Key words

TermMeaning
ObservabilityObservability lets you understand a system from the outside by letting you ask questions about that system without knowing its inner workings
InstrumentationTo ask those questions about your system, your application must be properly instrumented
TelemetryTelemetry refers to data emitted from a system and its behavior
MetricMetrics are aggregations over a period of time of numeric data about your infrastructure or application
LogA log is a timestamped message emitted by services or other components
SpanA span represents a single unit of work or operation
TraceA trace is made of one or more spans
Time seriesEvery time series is uniquely identified by its metric name and optional key-value pairs called labels
Labeloptional key-value pairs called labels
Instancean endpoint you can scrape is called an instance, usually corresponding to a single process
JobA collection of instances with the same purpose is called a job
upIts value is 1 if the instance is healthy, that is, reachable, or 0 if the scrape failed
CounterA counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart
GaugeA gauge is a metric that represents a single numerical value that can arbitrarily go up and down
HistogramA histogram records observations by counting them in configurable buckets
SummarySimilar to a histogram, a summary samples observations
PromQLPrometheus provides a functional query language called PromQL that lets the user select and aggregate time series data in real time
Instant vectorAn instant vector is a set of time series containing a single sample for each time series, all sharing the same timestamp
Range vectorA range vector is a set of time series containing a range of data points over time for each time series
Recording ruleRecording rules allow you to precompute frequently needed or computationally expensive expressions and save their result as a new set of time series
PendingAlerts which have not yet fired for long enough are considered pending
FiringAlerts are considered firing once they have been returned for this long
AlertmanagerThe Alertmanager takes care of deduplicating, grouping, and routing them to the correct receiver integration
GroupingGrouping categorizes alerts of similar nature into a single notification
InhibitionInhibition is a concept of suppressing notifications for certain alerts if certain other alerts are already firing
SilenceSilences are a straightforward way to simply mute alerts for a given time
Routing treeEvery alert enters the routing tree at the configured top-level route, which must match all alerts
promtoolYou can use promtool to test your rules
amtoola cli tool for interacting with the Alertmanager API
LokiLoki is a horizontally-scalable, highly-available, multi-tenant log aggregation system inspired by Prometheus
Log streamLabels allow Loki to organize and group together log messages into log streams
LogQLAll LogQL queries contain a log stream selector
Context propagationPropagation is the mechanism that moves context between services and processes
traceparentHTTP header field identifies the incoming request in a tracing system
Golden signalsthe four golden signals of monitoring are latency, traffic, errors, and saturation
CardinalityDo not use labels to store dimensions with high cardinality, such as user IDs, email addresses, or other unbounded sets of values

Reels on this topicএই টপিকের রিলস

Short videos from other creators, picked for this topic. They are not part of this page's fact-checked text. Nothing loads from YouTube until you press Play.অন্য ক্রিয়েটরদের বানানো ছোট ভিডিও, এই টপিকের জন্য বাছাই করা। এগুলো এই পেজের ফ্যাক্ট-চেক করা লেখার অংশ নয়। চালান বাটন চাপার আগে YouTube থেকে কিছুই লোড হয় না।

Show 3 more reelsআরও 3টি রিল দেখান
  1. [1]
    Observability primer

    OpenTelemetry Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  2. [2]
    What is OpenTelemetry?

    OpenTelemetry Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  3. [3]
    Context propagation

    OpenTelemetry Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  4. [4]
    Propagation (Python)

    OpenTelemetry Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  5. [5]
    Exporters (Python)

    OpenTelemetry Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  6. [6]
    Trace Context

    W3C Recommendation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  7. [7]
    Monitoring Distributed Systems

    Site Reliability Engineering (Google) · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  8. [8]
    Overview

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  9. [9]
    Data model

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  10. [10]
    Metric types

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  11. [11]
    Jobs and instances

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  12. [12]
    Querying basics

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  13. [13]
    Query functions

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  14. [14]
    Defining recording rules

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  15. [15]
    Alerting rules

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  16. [16]
    Unit testing for rules

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  17. [17]
    Exposition formats

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  18. [18]
    Metric and label naming

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  19. [19]
    Instrumentation

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  20. [20]
    Histograms and summaries

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  21. [21]
    Alerting

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  22. [22]
    Alerting overview

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  23. [23]
    Alertmanager

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  24. [24]
    Alertmanager configuration

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  25. [25]
    Alertmanager README (amtool)

    Prometheus Alertmanager on GitHub · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  26. [26]
    promtool

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  27. [27]
    HTTP API

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  28. [28]
    Management API

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  29. [29]
    prometheus command line

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  30. [30]
    Installation

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  31. [31]
    Loki overview

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  32. [32]
    Labels

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  33. [33]
    Label best practices

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  34. [34]
    Log queries

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  35. [35]
    Metric queries

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  36. [36]
    HTTP API

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  37. [37]
    Configuration examples

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  38. [38]
    Configuration reference

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  39. [39]
    Install Loki with Docker or Docker Compose

    Grafana Loki Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  40. [40]
    Operators

    Prometheus Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19

  41. [41]
    Traces

    OpenTelemetry Documentation · accessed 2026-11-19দেখা হয়েছে: 2026-11-19