Api Monitoring
By the end of this lesson you'll instrument a PHP API with structured logs, a health-check endpoint, latency percentiles, and correlation IDs — so when something breaks at 3 AM you can see exactly what, where, and why.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free Php course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1️⃣ The Three Pillars: Logs, Metrics, Traces
Observability is your ability to understand what's happening inside a running system just from the data it emits. It rests on three pillars. Logs are timestamped records of individual events ("a request was handled", "an error was thrown"). Metrics are numbers aggregated over time (requests per second, error rate, p95 latency) that you chart and alert on. Traces follow one request as it hops between services so you can see exactly where the time went. Logs tell you what happened, metrics tell you how often and how bad , and traces tell you where . This lesson builds all three from the ground up.
2️⃣ Structured Logging with Monolog
Structured logging means every log entry is a machine-readable object with consistent fields — level , message , timestamp , plus context — rather than a free-text sentence. The payoff is querying: "show me every level=error for user=u_004 in the last hour" becomes a one-line filter. In real PHP you'd reach for Monolog , the standard logging library (it implements PSR-3, the shared logging interface), and call log- error('msg', [...]) . The example below hand-rolls the same idea so you can see precisely what one structured log line is.
Each line is valid JSON with the same keys in the same shape. That consistency is the whole point: a log shipper (Datadog, Elasticsearch, Loki) can index every field, so you filter and chart logs instead of grepping plain text. Notice the level field — that single key is what separates routine info noise from the error you actually need to see.
3️⃣ Health-Check Endpoints
A health-check endpoint is a single URL — conventionally /health — that an uptime monitor or load balancer pings every few seconds. It checks your real dependencies (database, cache, queue) and returns HTTP 200 when everything is up or 503 (Service Unavailable) when something is down. The status code is what machines read: a load balancer that sees 503 stops sending traffic to that server, and an uptime monitor that sees 503 fires an alert. Keep the check fast and cheap — it runs constantly.
Here the cache is down, so the overall status flips to unhealthy and the endpoint returns 503 . In a real handler you'd call http_response_code( httpStatus) and send the JSON body. The per-dependency map ( database: up, cache: down ) tells the on-call engineer which thing broke without reading any logs.
4️⃣ Error Tracking & Uptime Monitoring
Logs are great for searching, but you don't want to read them to find out something broke. Error tracking tools like Sentry capture every uncaught exception, group identical errors together, count how often each fires, and message you with the stack trace and the request that caused it. Uptime monitoring (UptimeRobot, Pingdom, Better Stack) hits your health-check endpoint from outside your network on a schedule and alerts you the moment it stops returning 200 — catching the case where your whole server is down and can't even log. The pattern: logs to search, error tracking to be told, uptime to confirm you're reachable at all.
5️⃣ Latency Metrics & Percentiles
Latency is how long a request takes. Tracking only the average hides your worst experiences: if 99 requests take 40ms and one takes 4000ms, the average is a comfortable ~80ms — yet a real user waited four seconds. That's why teams track percentiles . p50 (the median) is a typical request; p95 means 95% of requests were at least this fast; p99 is your slow tail. Alerts go on p95/p99 because that's where users actually feel pain. Always pair percentiles with throughput (requests per second) and error rate .
Now you try. The script below emits a structured error log — fill in each ___ using the 👉 hint, then run it and compare against the Output panel.
One more. This one decides the HTTP status a health check should return. Fill in the operator and the failure code the hints point to.
6️⃣ Correlation IDs & Alerting
A correlation ID (also called a request ID or trace ID) is a unique string you generate the instant a request arrives — for example with bin2hex(random_bytes(8)) . You attach it to every log line that request produces and forward it in an X-Request-Id header to any service it calls. When something breaks, you search for that one ID and instantly see the full story of that single request across every service — instead of untangling thousands of interleaved lines. This is the seed of distributed tracing .
Alerting turns metrics into action. The goal is to be paged for things users feel — error rate climbing, p99 latency spiking, the health check failing — and nothing else. The enemy is alert fatigue : so many noisy alerts that the team mutes them all, including the real one. Guard against it by alerting on symptoms not internal blips, requiring a duration ("error rate over 5% for 5 minutes") so a one-second spike doesn't page anyone, and routing low-priority signals to a dashboard instead of a phone.
📋 Quick Reference — Monitoring & Observability
No code is filled in this time — just a brief and an outline. Compute the p95 latency yourself, run it on onecompiler.com/php or your own machine, then check your result against the expected output in the comments. This is the same write-run-check loop you'll use to build any real metric.
Practice quiz
What are the three pillars of observability?
- CPU, RAM, and disk
- Frontend, backend, and database
- Logs, metrics, and traces
- Errors, warnings, and info
Answer: Logs, metrics, and traces. Observability rests on logs (what happened), metrics (how often/bad), and traces (where the time went).
What does 'structured logging' mean?
- Each log entry is a machine-readable object with consistent fields (e.g. JSON)
- Logs are sorted alphabetically
- Logs are written in plain English sentences
- Logs are compressed to save space
Answer: Each log entry is a machine-readable object with consistent fields (e.g. JSON). Structured logs are objects with consistent fields (level, message, context) so a log tool can index and filter every field.
Which PHP library is the de-facto standard for logging and implements PSR-3?
- error_log
- PHPUnit
- Composer
- Monolog
Answer: Monolog. Monolog is the standard PHP logging library; it implements PSR-3, the shared logging interface.
A health-check endpoint should return which HTTP status when a dependency is down?
- 200 OK
- 503 Service Unavailable
- 404 Not Found
- 301 Moved Permanently
Answer: 503 Service Unavailable. A /health endpoint returns 200 when healthy and 503 when a dependency check fails, so monitors and load balancers can react.
Why is average latency misleading?
- It hides slow outliers that real users actually feel
- It is always larger than the real latency
- It only works for HTTP requests
- It cannot be charted
Answer: It hides slow outliers that real users actually feel. If 99 requests take 40ms and one takes 4000ms, the average is ~80ms — yet one user waited four seconds. Percentiles expose the slow tail.
What does p95 latency mean?
- The request took 95 milliseconds
- 95% of requests failed
- 95% of requests were at least this fast
- The 95th request in the log
Answer: 95% of requests were at least this fast. p95 means 95% of requests were at least this fast; p50 is the median and p99 is the slow tail.
What is a correlation ID used for?
- Encrypting log files
- Tying together all the log lines produced by one request across services
- Counting requests per second
- Naming the database connection
Answer: Tying together all the log lines produced by one request across services. A correlation (request/trace) ID is generated per request and attached to every log line, so you can follow one request across services.
Which tool captures uncaught exceptions and groups identical errors?
- Nginx
- Composer
- OPcache
- Sentry (error tracking)
Answer: Sentry (error tracking). Error-tracking tools like Sentry capture every uncaught exception, group identical ones, and alert you with the stack trace.
What is the best defence against alert fatigue?
- Send every alert to everyone
- Alert only on user-facing symptoms and require a duration threshold
- Disable all alerts
- Alert on every internal blip immediately
Answer: Alert only on user-facing symptoms and require a duration threshold. Alert on symptoms users feel (error rate, p99, health-check failing), add a duration so brief spikes don't page, and route low priority to a dashboard.
What does an uptime monitor (e.g. UptimeRobot) actually do?
- Compiles your PHP code faster
- Stores your session data
- Hits your health-check endpoint from outside on a schedule and alerts if it stops returning 200
- Encrypts database passwords
Answer: Hits your health-check endpoint from outside on a schedule and alerts if it stops returning 200. Uptime monitoring pings your health endpoint from outside the network and alerts the moment it stops returning 200 — even if the server can't log.