Logs and Monitoring: Error Rates, Percentiles and Alert Rules That Do Not Cry Wolf
Read a week of web server logs: count requests and errors per hour, compute the 95th percentile of response time, define an alert that needs several bad intervals in a row, rotate logs safely, and verify every figure with awk and Python.
In this lesson you will
- Read an access log line
- Compute error rates and percentiles
- Write an alert rule with a consecutive-interval condition
- Rotate and compress logs without losing lines
About 28 minutes
Something broke on Wednesday evening, and nobody knew until Thursday
A server writes a line to its access log for every request: the visitor’s address, the time, the request, the status code, the size, and often how long the request took. A week of a small site’s traffic is tens of thousands of lines, and the answers to the questions “was the site healthy?” and “when did it break?” are in them. Monitoring turns logs into numbers and numbers into alerts. The key figures are the request rate, the error rate, which is the share of responses with a status of 500 or above, and the latency, how long requests take. For latency the average hides the trouble, because a few very slow requests do not move it much, so percentiles are used: the 95th percentile is the time that 95 percent of requests beat, and a site whose average is 120 milliseconds can have a p95 of 900.
Alert rules decide when a person is woken. A rule that fires on a single bad minute cries wolf: any real site has an occasional error. A better rule needs the condition to hold for several intervals in a row, for example an error rate above 5 percent in each of three consecutive hours here, or five minutes in production, which filters the noise while still catching real outages. Every alert should name what to do. Logs themselves must be managed: a log file that grows for ever fills the disk and takes the server down, which is a classic outage. Log rotation renames the current file, starts a new one and compresses and deletes old ones after a retention period, and it must not lose lines or break the process that writes them.
| Figure | Definition | Watch for |
|---|---|---|
| Request rate | Requests per interval | Sudden drops as well as spikes |
| Error rate | Responses with status 500 or more, divided by all | Check client errors separately |
| p95 latency | Time that 95 percent of requests beat | Averages hide slow requests |
| Alert rule | Condition true for N intervals in a row | Too sensitive means ignored |
import random, sys, datetime, json
rng = random.Random(11)
start = datetime.datetime(2024, 3, 4)
lines = []
PATHS = ["/", "/shop", "/shop/cart", "/blog", "/api/orders", "/contact"]
for hour in range(7 * 24):
t0 = start + datetime.timedelta(hours=hour)
n = rng.randrange(150, 260) if 8 <= t0.hour <= 22 else rng.randrange(20, 60)
incident = 2 * 24 + 18 <= hour <= 2 * 24 + 20 # Wednesday 18:00 to 20:59 : the database is struggling
for _ in range(n):
ts = t0 + datetime.timedelta(seconds=rng.randrange(3600))
bad = rng.random() < (0.35 if incident else 0.006)
status = rng.choice([500, 502, 503]) if bad else rng.choices([200, 301, 404], [93, 4, 3])[0]
ms = int(rng.lognormvariate(4.6, 0.55) * (3.5 if incident else 1)) + 5
lines.append('10.0.%d.%d - - [%s] "GET %s HTTP/1.1" %d %d %d' % (rng.randrange(0, 30), rng.randrange(1, 250), ts.strftime("%d/%b/%Y:%H:%M:%S +0000"), rng.choice(PATHS), status, rng.randrange(300, 60000), ms))
lines.sort(key=lambda l: datetime.datetime.strptime(l.split("[")[1].split(" ")[0], "%d/%b/%Y:%H:%M:%S"))
open(sys.argv[1], "w").write("\n".join(lines) + "\n")
print("wrote", len(lines), "lines; the last field of each line is the time in milliseconds"); print(lines[0])
wrote 23738 lines; the last field of each line is the time in milliseconds
10.0.2.54 - - [04/Mar/2024:00:00:39 +0000] "GET /api/orders HTTP/1.1" 200 42019 85
f="$1"
echo "requests: $(wc -l < $f)"
echo "responses with status 500 or more: $(awk '$9 >= 500' $f | wc -l)"
echo "worst hours (day hour errors/requests):"
awk '{split($4, t, ":"); k = substr(t[1], 2, 2) " " t[2]; n[k]++; if ($9 >= 500) e[k]++} END {for (k in n) if (e[k] / n[k] > 0.05) printf " %s %d/%d\n", k, e[k], n[k]}' $f | sort
echo "p95 of the response time over all requests: $(awk '{print $NF}' $f | sort -n | awk '{a[NR]=$1} END {print a[int(NR*0.95 + 0.9999)]}') ms"
requests: 23738
responses with status 500 or more: 358
worst hours (day hour errors/requests):
05 00 2/29
06 18 70/172
06 19 68/192
06 20 77/235
10 23 2/28
p95 of the response time over all requests: 277 ms
import re, json, collections, math
rx = re.compile(r'^(\S+) - - \[(\d+)/(\w+)/(\d+):(\d+):(\d+):(\d+) \+0000\] "GET (\S+) HTTP/1.1" (\d+) (\d+) (\d+)$')
rows = [rx.match(x).groups() for x in open(r"/tmp/logs-7h3sahj1/access.log").read().strip().split("\n")]
hours = collections.defaultdict(lambda: [0, 0, []])
for g in rows: k = (int(g[1]), int(g[4])); hours[k][0] += 1; hours[k][1] += int(g[8]) >= 500; hours[k][2].append(int(g[10]))
def p95(x): s = sorted(x); return s[math.ceil(0.95 * len(s)) - 1]
mean_all = sum(int(g[10]) for g in rows) / len(rows)
print("overall: mean %.0f ms, p95 %d ms (the mean hides the slow tail)" % (mean_all, p95([int(g[10]) for g in rows])))
alerts, run = [], 0
for k in sorted(hours):
rate = hours[k][1] / hours[k][0]; run = run + 1 if rate > 0.05 else 0
if rate > 0.05: print("day %02d hour %02d: error rate %.1f%%, p95 %d ms" % (k[0], k[1], 100 * rate, p95(hours[k][2])))
if run == 3: alerts.append(k)
print("alert rule (error rate above 5% in 3 hours in a row) fires at:", alerts)
single = [k for k in hours if hours[k][1] / hours[k][0] > 0.05]
print("a rule that fires on any single bad hour would have fired", len(single), "times; hours with at least one error:", sum(1 for k in hours if hours[k][1] > 0), "of", len(hours))
print("DATA " + json.dumps({"alerts": alerts, "single": len(single), "err_hours": sum(1 for k in hours if hours[k][1] > 0), "mean": mean_all}))
overall: mean 127 ms, p95 277 ms (the mean hides the slow tail)
day 05 hour 00: error rate 6.9%, p95 233 ms
day 06 hour 18: error rate 40.7%, p95 941 ms
day 06 hour 19: error rate 35.4%, p95 740 ms
day 06 hour 20: error rate 32.8%, p95 881 ms
day 10 hour 23: error rate 7.1%, p95 238 ms
alert rule (error rate above 5% in 3 hours in a row) fires at: [(6, 20)]
a rule that fires on any single bad hour would have fired 5 times; hours with at least one error: 91 of 168
set -e
d=$(mktemp -d); cd "$d"
for i in $(seq 1 1000); do echo "line $i" >> app.log; done
cp app.log before.txt
cat app.log | wc -l | sed 's/^/lines before rotation: /'
mv app.log app.log.1; : > app.log # rotate: rename, then start a new empty file
for i in $(seq 1001 1200); do echo "line $i" >> app.log; done # the program keeps logging into the new file
gzip app.log.1
echo "files now: $(ls | tr '\n' ' ')"
echo "lines in the new log: $(wc -l < app.log) | lines in the compressed old log: $(zcat app.log.1.gz | wc -l)"
echo "nothing lost: $(( $(wc -l < app.log) + $(zcat app.log.1.gz | wc -l) )) lines in total"
echo "compressed size is $(stat -c %s app.log.1.gz) bytes, the original text was $(stat -c %s before.txt) bytes"
lines before rotation: 1000
files now: app.log app.log.1.gz before.txt
lines in the new log: 200 | lines in the compressed old log: 1000
nothing lost: 1200 lines in total
compressed size is 1981 bytes, the original text was 8893 bytes
The generated week holds 23,738 requests, and the awk pipeline and the Python script, which share no code, agree on every count: 358 responses with a status of 500 or more, an overall p95 of 277 milliseconds against a mean of 127, so the average hides a tail of slow requests, and 5 hours in which more than 5 percent of responses were errors. Three of them are the Wednesday-evening incident planted in the data, at hours 18, 19, 20 of day 06, with 70/172, 68/192, 77/235 errors and requests. The other two are quiet night hours, day 05 hour 00 and day 10 hour 23, with only 2 errors out of 29 and 2 out of 28 requests: with so little traffic, two errors are already more than 5 percent. That is a real property of rates over small samples, and the reason why a naive alert is noisy. Hours with at least one error numbered 91 out of 168.
The alert rule, an error rate above 5 percent in three hours in a row, fires once, at day 06 hour 20, after the third bad hour of the incident, and ignores the two isolated night hours. A simpler rule, firing on any single hour above 5 percent, would have fired 5 times here, three times for the real incident and twice for noise, and in a quieter system or with a lower threshold would have produced many false alarms. The cost of the three-in-a-row rule is delay, which is why production systems use minutes and not hours as the interval: the same logic with 5-minute intervals pages someone after 15 minutes of real trouble. A further refinement is to require a minimum number of requests in the interval, so that two errors on a quiet night do not count. Tuning is a trade between speed and noise, and a rule nobody trusts is worse than none.
The rotation experiment shows the safe order of events. A thousand lines were written, the log was renamed with mv and an empty file with the old name was created at once, and the program went on writing 200 more lines to the new file while the old one was compressed with gzip. Nothing was lost: 200 lines in the new file plus 1,000 in the compressed one make 1,200, and the compressed file is a small fraction of the size of the text. Real programs keep their file open by file handle, so after a rename they must be told to reopen the log, with a signal or by a rotation tool that copies and truncates, which is what logrotate offers, and forgetting this makes a service write to a deleted file while the disk fills.
Independent check: the totals, the error count, the three bad hours and the p95 were computed by awk and by Python from the same file and match, and the alert result was derived by two different loops. The p95 uses the nearest-rank method in both, the value at position ceil(0.95 x n) of the sorted list, and other definitions differ slightly, so the method is part of the definition. Reading the evidence in two tools is a habit to keep, because a dashboard that disagrees with the raw log is a bug worth finding.
Check by hand: with n requests, the nearest-rank p95 is the value at position ceil(0.95 n) when sorted. For 100 values it is the 95th. The three-in-a-row rule fires on the third consecutive bad hour, hour 20, because hours 18, 19 and 20 are all above the threshold.
Every alert needs an owner and a first step. If people learn to ignore alerts because most are noise, the real one will be missed. Remove or tune any rule that fires without action.
Error rate and latency matter to visitors. Disk space and memory matter as causes. Page for symptoms, and use causes for diagnosis and for early warnings that can wait until morning.
Providers, plans and prices change often, so the lessons use invented prices and generic names, and you must check each provider’s current website. The server behaviour in this lesson was run for real on a Linux machine with Python 3.13, Node.js 22, OpenSSL and standard Unix tools, and every result was checked a second way. Log formats differ between servers, and many tools collect and chart logs for you. The ideas of rates, percentiles and consecutive-interval rules apply to all of them.
Practice
Add a rule for latency: p95 above 800 milliseconds in three hours in a row. Count the requests per path with awk. Change the rotation to keep the last five compressed files and delete older ones.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why use percentiles instead of averages for latency?
- Percentiles are easier to type
- Averages hide the slow tail
- Averages are not numbers
- Servers report percentiles only
p95 shows what slow users feel.
Why require several intervals in a row for an alert?
- To avoid false alarms from isolated errors
- To delay all alerts
- To save disk
- It is a law
A trade between speed and noise.
What must a rotation not do?
- Lose lines or leave the program writing to a deleted file
- Compress files
- Rename files
- Keep old logs
Reopen the log after rotating.
What is the error rate?
- Responses with 404
- Requests per second
- Bytes per request
- Responses with status 500 or more divided by all
Client errors are separate.
Why check figures with awk and Python?
- To make the work longer
- Dashboards forbid it
- It is required
- Independent tools catch wrong parsing and definitions
Agree on the raw log.
Summary
- Turn logs into request rate, error rate and percentile latency.
- Alert on symptoms, with several intervals in a row.
- Rotate logs without losing lines, and compress them.
- Verify figures with a second tool.
Questions
How long should I keep logs?
Long enough to investigate problems and meet any legal duty, often weeks to months, and no longer than needed, since logs can contain personal data such as addresses. Check the rules that apply to you.
Do I need a monitoring service?
For anything important, yes: one outside your server that checks the site and alerts you, and ideally a tool that collects metrics. Many have free tiers.
What is a good request log format?
One line per request, with time, address, request, status, size and duration, in a consistent format that tools can parse.
