Log Analysis and Diagnostic Data Gathering Questions
Extracting signal from existing logs and diagnostic output to find a root cause: parsing and querying log data, correlating traces and metrics during an investigation, and gathering the right diagnostic information (including asking clarifying questions) before drawing conclusions. Covers text-processing and query techniques for locating evidence in logs (structured log parsing, ElasticSearch/SQL-style log queries, log aggregation and retention trade-offs) and reconstructing a timeline from the data on hand. This is the analysis-of-existing-data skill used during troubleshooting and investigation across infrastructure and operations roles: distinct from monitoring and observability, which is about instrumenting a system so telemetry exists in the first place (see the observability topics for that), and distinct from SIEM-based security detection and formal digital-forensics practice (chain of custody, artifact/disk/memory analysis), which have their own dedicated coverage elsewhere in the catalog.
Write a Python 3 script that reads a newline-delimited log file where each line is a JSON object with keys: "timestamp" (ISO 8601), "service", "level", "message". The script should output per-minute error counts (level == "ERROR") for a given service over the last 60 minutes, printing lines like: 2025-03-12 14:05 3. The log may be out-of-order and can be large (~10GB): prioritize streaming and bounded memory.
Sample Answer
Direct answer
Stream the file line by line and keep only a small dict of per-minute counters, never the raw lines, so memory stays bounded regardless of file size. Because the file can be out of order, the true 60-minute window boundary (which minute is "now") isn't known until you've seen the latest timestamp, so prune the counters dict opportunistically as later, larger timestamps arrive, rather than needing a full second pass over the file.
Approach
import json
from datetime import datetime, timedelta, timezone
WINDOW_MINUTES = 60
def _parse_ts(raw):
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
dt = datetime.fromisoformat(raw)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def per_minute_error_counts(path, service):
"""Stream a large NDJSON log file and return per-minute ERROR counts
for `service` over the last WINDOW_MINUTES relative to the latest
timestamp seen, as a dense list of (minute, count) tuples (one entry
per minute, zero-filled).
The file may be out of order. Rather than buffering every distinct
minute seen across the whole file, the counts dict is pruned WHILE
streaming: every time a new maximum timestamp arrives, anything
older than (new_max - WINDOW_MINUTES) is dropped. Memory therefore
stays close to O(WINDOW_MINUTES) even over a ~10GB file, at the cost
of one bookkeeping check per line rather than a second pass.
"""
counts = {}
newest = None
with open(path, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
if rec.get("service") != service:
continue
raw_ts = rec.get("timestamp")
if not raw_ts:
continue
try:
ts = _parse_ts(raw_ts)
except ValueError:
continue
if newest is None or ts > newest:
newest = ts
cutoff = newest - timedelta(minutes=WINDOW_MINUTES - 1)
for bucket in [b for b in counts if b < cutoff.replace(second=0, microsecond=0)]:
del counts[bucket]
if rec.get("level") == "ERROR":
bucket = ts.replace(second=0, microsecond=0)
counts[bucket] = counts.get(bucket, 0) + 1
if newest is None:
return []
window_start = (newest - timedelta(minutes=WINDOW_MINUTES - 1)).replace(second=0, microsecond=0)
result = []
cur = window_start
end = newest.replace(second=0, microsecond=0)
while cur <= end:
result.append((cur.strftime("%Y-%m-%d %H:%M"), counts.get(cur, 0)))
cur += timedelta(minutes=1)
return result
if __name__ == "__main__":
import os
path = "/tmp/loganalysis_b1_s18.ndjson"
lines = [
{"timestamp": "2025-03-12T14:05:10Z", "service": "checkout", "level": "ERROR", "message": "timeout"},
{"timestamp": "2025-03-12T13:00:00Z", "service": "checkout", "level": "ERROR", "message": "too old, outside 60min window"},
{"timestamp": "2025-03-12T14:05:40Z", "service": "checkout", "level": "ERROR", "message": "timeout"},
{"timestamp": "2025-03-12T14:59:59Z", "service": "checkout", "level": "ERROR", "message": "latest event, defines the window end"},
{"timestamp": "2025-03-12T14:05:20Z", "service": "checkout", "level": "INFO", "message": "not an error"},
{"timestamp": "2025-03-12T14:07:00Z", "service": "checkout", "level": "ERROR", "message": "timeout"},
{"timestamp": "2025-03-12T14:07:05Z", "service": "auth", "level": "ERROR", "message": "different service"},
]
with open(path, "w") as f:
for rec in lines:
f.write(json.dumps(rec) + "\n")
for bucket, cnt in per_minute_error_counts(path, "checkout"):
if cnt:
print(f"{bucket} {cnt}")
os.remove(path)
Worked example (executed output)
2025-03-12 14:05 2
2025-03-12 14:07 1
2025-03-12 14:59 1
The synthetic input above is deliberately out of order and mixes services and levels: a 13:00 entry (an hour before the latest timestamp, correctly excluded from the 60-minute window), an INFO-level entry at 14:05 (correctly excluded, not an ERROR), and an entry from a different service, auth (correctly excluded). The three surviving lines match exactly what the question's example output format specifies: YYYY-MM-DD HH:MM count.
Key points
- Memory stays close to
O(WINDOW_MINUTES), notO(distinct minutes in the whole file): every time a new maximum timestamp arrives, the code immediately drops any bucket older thannew_max - 60 minutes, rather than waiting until the end of the file to filter. Over a ~10 GB file that could span far more than an hour of wall-clock time, this keeps the counters dict small throughout the scan instead of growing with every minute the file happens to contain. - The underlying function returns a dense per-minute series (one entry per minute of the 60-minute window, zero-filled where there were no errors), which is more useful than a sparse series if you intend to plot it; the driver code above only prints non-zero minutes to match the requested output format, but the zero-filled minutes are still available from the function's return value.
- Out-of-order tolerance comes from tracking the running maximum timestamp seen so far, not from assuming the file's line order matches timestamp order at all.
Complexity
Time is O(n) for n lines in the file, one pass, no sorting. Space is bounded by the number of distinct minute buckets retained at any point, which the opportunistic pruning keeps close to the 60-minute window rather than proportional to the file's total time span.
Edge cases
- No matching lines at all (wrong service, or no ERROR-level entries): the function returns an empty list rather than guessing a window relative to wall-clock "now," since there's no timestamp evidence in the file to anchor a window to.
- All events in the same single minute: the loop still correctly walks the full 60-minute range and reports that one minute's count alongside 59 zero counts in the dense series.
- A timestamp that fails to parse: skipped rather than raised, so one malformed line doesn't abort processing of a 10 GB file.
Trade-offs & pitfalls
The main design decision worth defending is anchoring "last 60 minutes" to the latest timestamp actually seen in the file, rather than to wall-clock now(). For a file being analyzed after the fact (which is the realistic scenario for "you're handed a log file and asked to find the error pattern"), the data's own latest timestamp is the meaningful reference point; anchoring to now() instead would silently produce an empty or wrong window whenever the file isn't from the current moment, which is the common case during an investigation. The trade-off of opportunistic pruning versus a simpler two-pass approach (scan once for the max timestamp, then scan again to aggregate) is one pass of I/O saved at the cost of slightly more bookkeeping per line; for a 10 GB file, halving the required I/O is worth that complexity.
Demonstrate practical journalctl usage: give commands and short explanations for the following tasks:
- List all boots and show the last boot's ID
- Show logs for unit nginx.service filtered to warning and above
- Follow logs in real time for a unit
- Export journal entries in JSON for downstream parsing
Also explain the significance of fields like _SYSTEMD_UNIT and _PID in the journal.
Sample Answer
Direct answer
journalctl is the query tool for the systemd journal, the structured binary log store used by most modern Linux distributions alongside (or instead of) flat files in /var/log. The four commands below are standard, documented journalctl usage; they are shown as reference commands rather than a captured run, since this environment has no systemd journal to query against.
Structured elaboration
1) List all boots and show the last boot's ID
journalctl --list-boots
journalctl --list-boots | tail -n 1
--list-boots prints one line per system boot: a relative index (0 is the current boot, -1 the previous one, and so on), the boot ID, and its start/end timestamps. The last line of that output is the most recent boot; its second column is the boot ID you'd pass to journalctl -b <ID>.
2) Show logs for nginx.service filtered to warning and above
journalctl -u nginx.service -p warning
-p (priority) filters by syslog severity. Passing a single level like warning means "this level or anything more severe" (warning, error, critical, alert, emergency), matching "warning and above."
3) Follow logs in real time
journalctl -u nginx.service -f
-f behaves like tail -f: it prints new entries as they're written instead of exiting after the current buffer.
4) Export entries as JSON for downstream parsing
journalctl -u nginx.service -o json
-o json emits one JSON object per line, not json-pretty, which spans multiple lines per entry and is awkward to stream. One-object-per-line is what lets a downstream parser (jq, a Python script, a log shipper) read the output incrementally.
Field significance
_SYSTEMD_UNITidentifies which systemd unit emitted the entry. On a host running many services, this is what lets you filter (journalctl -u <unit>) or, when reading exported JSON, group entries by service without relying on message text._PIDis the originating process ID. It matters when a unit forks multiple worker processes (a pre-fork web server, a pool of workers): grouping by_PIDlets you isolate the specific worker instance a request or crash came from, which you often need when correlating with a process-level diagnostic taken from that same PID.
Worked example
Given a hypothetical JSON export like:
{"_SYSTEMD_UNIT":"nginx.service","_PID":"4213","MESSAGE":"worker process started"}
{"_SYSTEMD_UNIT":"nginx.service","_PID":"4214","MESSAGE":"worker process started"}
{"_SYSTEMD_UNIT":"nginx.service","_PID":"4213","MESSAGE":"connection reset by peer"}
Piping this through jq -r 'select(._PID=="4213") | .MESSAGE' isolates only the events from PID 4213, showing that specific worker hit the reset, not its sibling on PID 4214, a distinction the raw message text alone would not make.
Trade-offs & pitfalls
A common mistake is filtering only by unit and assuming that captures everything relevant. A crash can leave entries under kernel (an out-of-memory kill) or under systemd itself (a unit that failed to even start) that never carry _SYSTEMD_UNIT=nginx.service. When a unit-scoped query comes up empty or incomplete, widen to journalctl -k for the kernel ring buffer, or drop the unit filter for a plain time-window query, before concluding the journal has nothing.
During an incident retro, you go looking for the application log from four days ago and it's gone; only the last couple of days of rotated files still exist. Walk through how you'd figure out whether that's expected retention behavior or a rotation misconfiguration, and what you'd check or change so it doesn't bite the next investigation.
Sample Answer
Direct answer
Start from the config: read the logrotate (the standard Linux utility that rotates, compresses, and deletes log files on a schedule) stanza for this application and work out how many days of history it's actually supposed to retain, since "only 2 days survive" might be exactly what the config says, just not what anyone expected. If the config genuinely promises more than 2 days, the next question is whether rotation is happening more often than assumed, most commonly because it's triggered by file size, not purely by a daily schedule, and a burst of logging quietly burned through the retention budget faster than usual.
Structured elaboration
- Read the actual config, don't assume it says what people remember. Find the stanza for this app (typically under
/etc/logrotate.d/) and checkrotate N(how many old copies to keep before deleting), and whether rotation isdaily/weeklyorsize-triggered (e.g.size 100M). A config withrotate 14genuinely only promises 14 rotation cycles, not 14 calendar days, those are the same thing only if rotation is purely time-based and never fires early. - Check whether rotation is size-triggered and could have fired more than once a day. This is the most common surprise: if the stanza has a
sizedirective (ormaxsizealongsidedaily), a burst of unusually verbose logging (a bug spamming warnings, a traffic spike) can trigger multiple rotations in a single day. If that happened,rotate 14might only cover 3-4 calendar days instead of 14, and the config was never wrong, the assumption that "rotation count equals days" was. - Check when rotation actually last ran and how often. Logrotate records the last rotation timestamp per config stanza in a status file (commonly
/var/lib/logrotate/statuson newer Debian/Ubuntu packaging, or/var/lib/logrotate.statuson some older systems, check whichever exists on this host). Comparing that against the timestamps on the surviving rotated files (ls -la --time-style=full-iso /var/log/myapp/*.gz) tells you the actual rotation cadence over the retention window, not the cadence the config implies. - Rule out something deleting files outside logrotate entirely. A disk-pressure cleanup cron job, a container image rebuild that wiped a non-persistent volume, or a manual cleanup someone ran and forgot about can all produce the exact same symptom as a rotation misconfiguration. Check for other scheduled jobs touching that directory (
grep -r logrotate /etc/cron*, and anything else withfind/rmagainst/var/log/myapp) before concluding it's purely alogrotateissue. - Dry-run the config to see what it would actually do right now.
logrotate -d /etc/logrotate.d/myappruns a dry run (debug mode: shows what actions would be taken without taking them), which is the fastest way to confirm your reading of the stanza matches what logrotate itself thinks it should do, catching a typo or an unexpected included/overriding config you missed on a manual read.
Worked example
# 1. What does the config actually promise?
cat /etc/logrotate.d/myapp
# e.g.:
# /var/log/myapp/application.log {
# daily
# rotate 14
# size 100M
# compress
# }
# This promises "up to 14 rotations, whichever of daily/100M triggers first"
# -- NOT unconditionally 14 calendar days.
# 2. When did each surviving rotation actually happen, and how big were they?
ls -la --time-style=full-iso /var/log/myapp/application.log*.gz
# 3. What does logrotate's own status file say about last-rotation timing?
cat /var/lib/logrotate/status 2>/dev/null || cat /var/lib/logrotate.status 2>/dev/null
# 4. Confirm the config parses the way you think it does, without applying it.
logrotate -d /etc/logrotate.d/myapp
If step 2's timestamps show several rotations within a single day around the time of a known traffic spike or noisy deploy, that's a strong, checkable signal that size 100M fired early and repeatedly, burning through the 14-rotation budget in far fewer than 14 days, exactly the "expected behavior, unexpected outcome" case rather than a misconfiguration.
What to change so it doesn't bite the next investigation
- If size-triggered rotation is the cause, either raise
rotate Nenough to cover your actual worst-case rotation cadence during a noisy period, or addmaxagesemantics via a longer retention window, or (often the real fix) ship logs off-host to a central store where retention isn't coupled to a single host's disk and a burst of local logging can't shrink your effective history. - If the config is genuinely fine and the real gap is "logrotate's local retention was never meant to serve as your incident-investigation retention," that's a signal the two need to be decoupled: local rotation exists to bound disk usage, not to be the system of record for four-day-old incident evidence.
- Whatever the root cause, document the actual effective retention (in calendar days, under realistic worst-case log volume) somewhere a future investigator will find it before they hit the same surprise.
Trade-offs & pitfalls
rotate Nwith a size trigger is a genuinely reasonable config for bounding disk usage; the mistake isn't the config, it's treating "N rotations" and "N days" as interchangeable when planning how far back an investigation can reach.- Raising
rotate Njust enough to cover today's worst case doesn't protect against tomorrow's worse case (a bigger traffic spike, a noisier bug); if four-day-plus retention actually matters for incident response, local rotation on a single host is the wrong system to depend on at all.
Describe a small utility or automation (pseudocode or high-level steps) you would implement in Python to scan metrics or logs and identify the top services with rising error rates over a sliding 24-hour window. State inputs, outputs, aggregation method, and threshold logic.
Sample Answer
Direct answer
Pull per-service error and request counts for the last 24 hours and the 24 hours before that, compute each service's error rate (errors divided by requests) in both windows, and rank services by how much that rate increased, with a minimum absolute-error floor so a service going from 1 error to 2 doesn't dominate the list.
Structured elaboration
- Inputs: two time-bounded queries against your metrics or log backend (Prometheus, an ELK-style log store, or a data warehouse table):
current_windowcovering[now - 24h, now]andprevious_windowcovering[now - 48h, now - 24h], each returning(service, error_count, request_count)rows. - Aggregation method: sum errors and requests per service within each window (this is a single
GROUP BY servicein whichever backend you're querying), then computeerror_rate = errors / requestsfor each service in each window. - Threshold logic: flag a service as "rising" only if both hold: (1) the percentage increase in error rate versus the previous window exceeds a chosen threshold (e.g. 50%), and (2) the current window has at least some minimum absolute error count (e.g. 20). The second condition matters because a rate can double from a statistically meaningless base (1 error to 2) without being operationally significant; the floor filters that noise out.
- Output: a ranked list of
(service, percent_increase, current_rate, current_error_count), truncated to the top N (e.g. top 3), suitable for a Slack message or a dashboard panel.
Worked example
def find_rising_services(current, previous, top_n=3, pct_threshold=50.0, min_errors=20):
results = []
for service in set(current) | set(previous):
cur = current.get(service, {"errors": 0, "requests": 1})
prev = previous.get(service, {"errors": 0, "requests": 1})
rate_cur = cur["errors"] / (cur["requests"] or 1)
rate_prev = prev["errors"] / (prev["requests"] or 1)
pct_increase = ((rate_cur - rate_prev) / rate_prev * 100 if rate_prev > 0
else 100.0 if rate_cur > 0 else 0.0)
if cur["errors"] >= min_errors and pct_increase >= pct_threshold:
results.append((service, pct_increase, rate_cur, cur["errors"]))
results.sort(key=lambda r: r[1], reverse=True)
return results[:top_n]
Run against pinned example data for four services (current vs. previous 24h window):
current_window = {
"checkout": {"errors": 480, "requests": 40000},
"search": {"errors": 55, "requests": 50000},
"auth": {"errors": 12, "requests": 30000},
"recommend": {"errors": 300, "requests": 20000},
}
previous_window = {
"checkout": {"errors": 200, "requests": 39000},
"search": {"errors": 50, "requests": 49000},
"auth": {"errors": 10, "requests": 29500},
"recommend": {"errors": 40, "requests": 19800},
}
for service, pct, rate, errs in find_rising_services(current_window, previous_window):
print(f"{service:<10} +{pct:6.1f}% current rate={rate:.4%} errors={errs}")
Output:
recommend + 642.5% current rate=1.5000% errors=300
checkout + 134.0% current rate=1.2000% errors=480
search (7.8% increase) and auth (18% increase, and only 12 errors, below the floor) are correctly excluded: their rate barely moved and/or their volume is too low to act on.
Trade-offs & pitfalls
- Comparing only two adjacent 24-hour windows is sensitive to day-of-week effects (a Monday will look "worse" than a quiet Sunday even with no real regression); a production version would compare against the same weekday a week prior, or a rolling baseline, instead.
- A hard percentage threshold treats a jump from 0.001% to 0.002% the same as 10% to 20% unless the minimum-error floor is tuned well; the floor is doing real work here, not just cosmetic filtering.
- This is a scan-and-report utility, not a real-time alert; running it every few minutes as a scheduled job is usually enough, since "rising over 24h" is inherently a slow-moving signal, not something that needs sub-second reaction.
Write (or outline) a Python script that reads a large log file (streaming, may not fit in memory) of timestamped events where each line is: "ISO8601_TIMESTAMP LEVEL message". Implement an approach to identify the top-3 sliding 5-minute windows with the highest error (LEVEL=ERROR) rate and report window start, end, and error count. Explain complexity and streaming constraints.
Sample Answer
Direct answer
Stream the file line by line (never load it whole), keep only ERROR timestamps that fall inside the trailing 5-minute window in a deque (a double-ended queue that supports cheap removal from either end), and every time a new ERROR arrives, record the current window's (count, start, end) into a size-3 min-heap (a small structure that always exposes the smallest of the items it holds). At the end, the heap holds the 3 highest counts seen at any point in the stream.
Structured elaboration
ISO8601 here refers to the standard YYYY-MM-DDTHH:MM:SS timestamp format, so parsing is a direct datetime.fromisoformat() call rather than custom string-splitting.
- Read the file one line at a time (
for line in f), which keeps memory bounded by one line at a time, not the whole file. - Parse each line into
(timestamp, level, message). Skip anything that isn'tLEVEL=ERROR; non-ERROR lines don't affect the window count and can be discarded immediately. - For each ERROR event: append its timestamp to a deque, then pop from the left while the oldest timestamp is more than 5 minutes older than the current one. The deque now holds exactly the ERROR timestamps in the trailing 5-minute window, and its length is the window's error count.
- Push
(count, window_start, window_end)onto a min-heap capped at size 3. If the heap is full and the new count beats the heap's smallest entry, replace it (heapreplace); otherwise it's discarded immediately with no further work. - At the end, sort the heap's 3 entries descending by count for reporting.
Worked example
import heapq
from collections import deque
from datetime import datetime, timedelta
WINDOW = timedelta(minutes=5)
TOP_K = 3
def parse_line(line):
ts_raw, level, *_ = line.split(" ", 2)
return datetime.fromisoformat(ts_raw), level
def top_windows_from_stream(lines):
errors = deque() # ERROR timestamps currently inside the trailing 5-min window
topk = [] # min-heap of (count, window_start, window_end)
for line in lines:
ts, level = parse_line(line)
if level != "ERROR":
continue
errors.append(ts)
cutoff = ts - WINDOW
while errors and errors[0] < cutoff:
errors.popleft()
window = (len(errors), errors[0], ts)
if len(topk) < TOP_K:
heapq.heappush(topk, window)
elif window[0] > topk[0][0]:
heapq.heapreplace(topk, window)
return sorted(topk, key=lambda w: (-w[0], w[1]))
I ran this against a pinned synthetic log with three separate ERROR bursts (three, five, and four ERROR lines respectively, spaced far enough apart to be independent), interspersed with INFO noise:
base = "2026-01-01T00:{:02d}:{:02d}"
synthetic_lines = (
[base.format(m, s) + " ERROR burst-a" for m, s in [(0, 0), (1, 0), (1, 30)]]
+ [base.format(3, 0) + " INFO heartbeat"]
+ [base.format(m, s) + " ERROR burst-b" for m, s in [(10, 0), (10, 45), (11, 30), (12, 15), (13, 0)]]
+ [base.format(15, 0) + " INFO heartbeat"]
+ [base.format(m, s) + " ERROR burst-c" for m, s in [(20, 0), (20, 40), (21, 20), (22, 0)]]
) # bursts of 3, 5, and 4 ERROR lines respectively
results = top_windows_from_stream(synthetic_lines)
for count, start, end in results:
print(f"{count} errors [{start.isoformat()} -> {end.isoformat()}]")
Output:
5 errors [2026-01-01T00:10:00 -> 2026-01-01T00:13:00]
4 errors [2026-01-01T00:10:00 -> 2026-01-01T00:12:15]
4 errors [2026-01-01T00:20:00 -> 2026-01-01T00:22:00]
I cross-checked the top-1 count independently with a brute-force O(n^2) scan (for every ERROR timestamp, count ERRORs within 5 minutes before it, ignoring the streaming algorithm entirely) and it also found 5 as the maximum, confirming the streaming result is correct.
Complexity and streaming constraints
- Time:
O(n log k)wherenis the number of lines andk=3. Each line doesO(1)amortized deque work (each timestamp is pushed and popped from the deque at most once across the whole run) plus at most oneO(log k)heap operation, andk=3makes that heap cost negligible in practice. - Space:
O(m + k)wheremis the number of ERROR events that can exist inside any single 5-minute window (bounded by your event rate, not file size) andk=3for the heap. The file's total size never appears in the memory bound, which is exactly the streaming constraint the question asks about: memory scales with event density, not with file size. - Streaming constraint: the algorithm makes exactly one forward pass, never seeking backward, so it works unchanged whether the input is a local file, a piped stream, or a network socket.
Trade-offs & pitfalls
- This assumes timestamps arrive in non-decreasing order (true for a single process's own log file). Out-of-order lines (common when merging logs from multiple hosts) break the deque's "oldest is always at the front" invariant; you'd need a small out-of-order buffer or an external sort-by-timestamp pass first.
- The top-3 windows found this way can overlap heavily, as in the example above where windows 1 and 2 are both anchored in the same burst. If the interviewer wants 3 distinct, non-overlapping worst periods, add a step that discards any candidate window overlapping an already-selected one (a small non-maximum-suppression pass) before taking the top 3.
- Malformed lines (wrong field count, unparsable timestamp) should be counted and logged, not silently dropped, or you risk under-reporting error bursts without anyone noticing the pipeline is quietly losing data.
Unlock Full Question Bank
Get access to all 27 Log Analysis and Diagnostic Data Gathering interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.