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.
Given the following log line format: '2025-05-01T12:34:56Z level=error srv=payments request_id=abc123 user_id=42 msg="checkout failed" latency_ms=562', write a Python function that parses arbitrary lines conforming to this structure into a dictionary, handles missing keys gracefully, and converts numeric fields. Provide example input and expected output.
Sample Answer
Direct answer
Split the leading timestamp token off, then pull every key=value pair with a regex that also handles quoted values containing spaces (like msg="checkout failed"), and convert values that look numeric into int/float. Keys that never appear in a given line simply never get a dict entry, so callers should use .get(key, default) rather than assuming every key is always present.
Approach
import re
KV_RE = re.compile(r'(\w+)=("[^"]*"|\S+)')
def parse_log_line(line):
"""Parse a line like:
2025-05-01T12:34:56Z level=error srv=payments request_id=abc123 ...
into a dict. The leading token (no '=') is treated as the timestamp.
Numeric-looking values are converted to int/float. Missing keys simply
do not appear in the result (callers should use dict.get with a default).
"""
parts = line.strip().split(" ", 1)
if not parts:
return {}
result = {}
if "=" not in parts[0]:
result["ts"] = parts[0]
rest = parts[1] if len(parts) > 1 else ""
else:
rest = line.strip()
for key, raw_val in KV_RE.findall(rest):
val = raw_val.strip('"')
if re.fullmatch(r'-?\d+', val):
val = int(val)
elif re.fullmatch(r'-?\d+\.\d+', val):
val = float(val)
result[key] = val
return result
line1 = ('2025-05-01T12:34:56Z level=error srv=payments request_id=abc123 '
'user_id=42 msg="checkout failed" latency_ms=562')
line2 = '2025-05-01T12:35:10Z level=info srv=payments msg="health check ok"'
for line in (line1, line2):
parsed = parse_log_line(line)
print(parsed)
print(" user_id:", parsed.get("user_id", "MISSING"))
Worked example (executed output)
{'ts': '2025-05-01T12:34:56Z', 'level': 'error', 'srv': 'payments', 'request_id': 'abc123', 'user_id': 42, 'msg': 'checkout failed', 'latency_ms': 562}
user_id: 42
{'ts': '2025-05-01T12:35:10Z', 'level': 'info', 'srv': 'payments', 'msg': 'health check ok'}
user_id: MISSING
Key points
- The regex
(\w+)=("[^"]*"|\S+)matches a bare key, then either a double-quoted value (captured without its quotes) or a plain whitespace-delimited value; this is what correctly keeps"checkout failed"as one value instead of splitting on the space inside it. - Numeric conversion is deliberately conservative: only strings that are entirely digits (with an optional leading
-) becomeint, and only a simple-?\d+\.\d+shape becomesfloat. Everything else, includingrequest_id=abc123, stays a string, which avoids accidentally coercing an alphanumeric ID that happens to start with digits. - Missing keys are absent, not
None. The second example line has nouser_idat all, andparsed.get("user_id", "MISSING")shows that explicitly, which is the "handle missing keys gracefully" behavior the question asks for.
Complexity
O(n) time and O(k) space, where n is the line's length and k is the number of key=value pairs, since the regex makes a single pass and each match does constant-time work.
Edge cases
- A key that appears twice: the current implementation lets the later occurrence overwrite the earlier one, since it's just a dict assignment in a loop; if you needed to preserve repeats, you'd collect values into a list instead.
- A value that looks numeric but isn't meant to be, like a zip code
user_zip=02139: this would be silently converted to the integer2139, losing the leading zero. If exact string preservation matters for some fields, you'd need a field-name allowlist for numeric conversion rather than converting anything digit-shaped. - Malformed tokens (a stray
=with nothing after it, or unbalanced quotes) simply fail to match the regex and are skipped rather than raising, which keeps the parser from crashing on one bad line in a large file.
Trade-offs & pitfalls
The main trade-off is permissiveness versus strictness: this parser is intentionally lenient (skip what doesn't match, coerce what looks numeric) because production log parsing usually needs to tolerate slightly malformed input rather than halt on it. The cost is exactly the zip-code-style edge case above, where "looks numeric" and "is semantically numeric" diverge; a stricter, schema-aware parser would need to know in advance which fields are genuinely numeric.
You are given the following snippet from production logs and traces. Analyze the events and identify the most likely root cause and the immediate mitigation steps you would take. Logs:
2025-11-10T10:02:15.101Z service-A trace=abc123 request=R1 status=200 latency_ms=120
2025-11-10T10:02:15.201Z service-B trace=abc123 request=R1 status=500 error="DB timeout"
2025-11-10T10:02:15.301Z service-A trace=abc123 request=R1 status=200 retry=1
2025-11-10T10:02:16.000Z service-C trace=def456 request=R2 status=503
Provide a reasoned RCA hypothesis and at least three concrete verification steps and mitigations.
Sample Answer
Direct answer
Reading the four lines directly: request R1 (trace abc123) called service-B, which returned a 500 with a "DB timeout" error; service-A then retried and got a 200 on the same trace, meaning the client-side retry masked the failure from the caller. A separate request R2 (trace def456) hit service-C and got a 503 with no retry visible. The most likely root cause is a transient database or downstream-dependency slowdown around 10:02:15, severe enough to time out service-B's call and to also affect service-C, whether directly or through a shared dependency; the fact that a retry immediately succeeded on R1 points at a transient condition rather than a hard failure.
Structured elaboration
Rather than eyeballing four lines by hand, group log lines by trace ID programmatically. That scales to a real incident with thousands of lines, and it's the same operation you'd reach for first when actually triaging this:
import re
from collections import defaultdict
LOG = """\
2025-11-10T10:02:15.101Z service-A trace=abc123 request=R1 status=200 latency_ms=120
2025-11-10T10:02:15.201Z service-B trace=abc123 request=R1 status=500 error="DB timeout"
2025-11-10T10:02:15.301Z service-A trace=abc123 request=R1 status=200 retry=1
2025-11-10T10:02:16.000Z service-C trace=def456 request=R2 status=503
"""
KV_RE = re.compile(r'(\w+)=("[^"]*"|\S+)')
def parse_line(line):
ts, service, rest = line.split(" ", 2)
fields = {"ts": ts, "service": service}
for key, val in KV_RE.findall(rest):
fields[key] = val.strip('"')
return fields
events = [parse_line(l) for l in LOG.strip().splitlines()]
by_trace = defaultdict(list)
for e in events:
by_trace[e["trace"]].append(e)
for trace_id, evs in by_trace.items():
evs.sort(key=lambda e: e["ts"])
print(f"trace={trace_id}")
had_error = False
recovered = False
for e in evs:
status = int(e["status"])
tag = ""
if status >= 500:
had_error = True
tag = f" <- ERROR ({e.get('error', 'no error field')})"
if e.get("retry") and status < 500:
recovered = True
tag = " <- succeeded after retry"
print(f" {e['ts']} {e['service']} status={status}{tag}")
verdict = "recovered via client-side retry" if (had_error and recovered) else (
"unresolved failure, no retry observed" if had_error else "no error")
print(f" verdict: {verdict}\n")
Worked example (executed output)
trace=abc123
2025-11-10T10:02:15.101Z service-A status=200
2025-11-10T10:02:15.201Z service-B status=500 <- ERROR (DB timeout)
2025-11-10T10:02:15.301Z service-A status=200 <- succeeded after retry
verdict: recovered via client-side retry
trace=def456
2025-11-10T10:02:16.000Z service-C status=503 <- ERROR (no error field)
verdict: unresolved failure, no retry observed
Grouping by trace ID and looking at each trace's outcome is exactly what separates the two requests here: R1 resolved (error, then a successful retry, one clean causal story), while R2 is still an open, unresolved failure with no evidence of recovery in this snippet.
Verification steps
- Pull database or downstream-dependency metrics (CPU, connection count, query latency) for the
10:02:15to10:02:16window; a timeout error alone doesn't tell you whether the database was overloaded, a specific query was slow, or the network path was degraded. - Check service-B's own logs and metrics for connection pool exhaustion or a spike in outstanding requests right before the timeout, since that would point at capacity rather than the database itself.
- Check whether service-C shares the same downstream dependency as service-B (same database, same connection pool, same upstream service); if so, the two failures likely share one root cause rather than being coincidental.
- Check for a recent deploy or configuration change in the few minutes before
10:02:15; a narrowed connection pool or a newly slow query are common self-inflicted causes of exactly this pattern.
Trade-offs & pitfalls
The tempting mistake is treating R1 as "fine" because it eventually returned 200. A retry that masks a transient failure is still evidence of degradation, and if service-A's retries are not rate-limited, a burst of retries during a real outage can amplify load on the already-struggling dependency, turning a transient blip into a cascading one. The other trap is treating R2's bare 503 as unrelated just because it's a different trace and a different service; two failures in the same one-second window sharing infrastructure are worth checking for a common cause before assuming they're independent.
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.
On a typical Linux system, where are system and application logs stored by default and what are the differences between text-based files under /var/log and the systemd journal? Include example commands to:
- View the last 100 lines of a file-based log
- Show logs for a specific systemd unit since yesterday
- Follow a log file in real time
Explain when one source may contain entries the other does not and the implications for incident response.
Sample Answer
Direct answer
/var/log holds traditional, plain-text log files (one file per service or subsystem, rotated by logrotate). The systemd journal is a separate, structured binary log store, written and queried through journald/journalctl, that many modern distributions use alongside or instead of writing directly to /var/log. They can disagree about what happened during an incident, so a thorough investigation checks both rather than assuming one is a superset of the other.
Structured elaboration
- Format:
/var/logfiles are plain text, so any text tool (grep,tail,awk) works directly. The journal stores structured fields (timestamp, unit, PID, priority, and more) in a binary format that requiresjournalctlto read. - Coverage: services that write to standard output/error under systemd have their output captured by the journal automatically. A service that opens its own file and writes to it directly (a legacy daemon with hardcoded file logging) may never reach the journal at all unless something explicitly forwards it.
- Retention:
/var/logfiles are rotated bylogrotateon a schedule and size/count policy you configure. The journal has its own separate size/time limits (SystemMaxUse,SystemMaxFileSize, and similar settings injournald.conf), which can differ from yourlogrotatepolicy and quietly expire data on a different schedule than you expect. - Early boot: the journal can capture kernel and early-boot messages before user-space logging daemons have even started, something a
/var/logfile typically cannot do, since the process that would write it isn't running yet.
Worked example
# View the last 100 lines of a file-based log
tail -n 100 /var/log/syslog
# Show logs for a specific systemd unit since yesterday
journalctl -u nginx.service --since yesterday
# Follow a log file in real time
tail -f /var/log/nginx/access.log
Suppose nginx.service fails to start at all because of a bad config file. Systemd's own record of that failure (the unit failing to activate) lives in the journal, associated with the unit; nginx itself never got far enough to write anything into /var/log/nginx/error.log, since the process never fully started. Grepping only /var/log/nginx/error.log here would find nothing, while journalctl -u nginx.service --since yesterday would show the startup failure.
Trade-offs & pitfalls
The common mistake during incident response is picking one source and treating it as complete. Relying only on /var/log risks missing early-boot events, systemd-level failures, and anything a service only ever sent to standard output. Relying only on the journal risks missing legacy daemons that write directly to files and were never wired into journald, or log lines that already rotated out of the journal's own retention window while an older /var/log archive still has them. When the two disagree about whether something happened, that disagreement is itself a useful signal about how the service is (or isn't) integrated with systemd, not just an annoyance to work around.
Coding task in Python: build a memory-efficient utility that reads multiple large newline-delimited JSON log files and extracts, in chronological order, all events that have a given request_id between two timestamps. The function signature should be extract_events(file_paths, request_id, start_ts, end_ts) and must stream files without loading them entirely into memory. Describe edge cases you would handle in production.
Sample Answer
Direct answer
Stream each file line by line rather than reading it into memory, filter to the matching request_id and timestamp range as you go, and merge the per-file streams with a k-way merge, using a min-heap (a small structure that always exposes the smallest of the items it holds) keyed by timestamp, so the combined output comes out globally chronological without ever holding more than one buffered record per file at once.
Approach
import json
import heapq
from datetime import datetime
def _parse_ts(raw):
return datetime.fromisoformat(raw.replace("Z", "+00:00"))
def _file_matches(path, request_id, start_ts, end_ts):
"""Stream one file line by line. Assumes each file is internally
time-ordered (true of an append-only log file), so this generator
yields matching events in ascending timestamp order for THIS file.
Never holds more than the current line in memory.
"""
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("request_id") != request_id:
continue
raw_ts = rec.get("ts")
if raw_ts is None:
continue
try:
event_ts = _parse_ts(raw_ts)
except ValueError:
continue
if start_ts <= event_ts <= end_ts:
rec["_ts_parsed"] = event_ts
yield rec
def extract_events(file_paths, request_id, start_ts, end_ts):
"""Yield events with the given request_id whose timestamp falls in
[start_ts, end_ts], in chronological order, across multiple large
NDJSON log files, without loading any file fully into memory.
Each file is scanned by its own generator (bounded to one open line
at a time); a min-heap does a k-way merge across those generators so
only one buffered record per file is held at once, not all matches.
Memory is O(number of files), not O(file size) or O(match count).
"""
heap = []
iterators = [iter(_file_matches(p, request_id, start_ts, end_ts)) for p in file_paths]
for idx, it in enumerate(iterators):
first = next(it, None)
if first is not None:
heapq.heappush(heap, (first["_ts_parsed"], idx, first))
while heap:
ts, idx, rec = heapq.heappop(heap)
del rec["_ts_parsed"]
yield rec
nxt = next(iterators[idx], None)
if nxt is not None:
heapq.heappush(heap, (nxt["_ts_parsed"], idx, nxt))
if __name__ == "__main__":
import os
file_a = "/tmp/loganalysis_b1_s13_a.ndjson"
file_b = "/tmp/loganalysis_b1_s13_b.ndjson"
# file_a and file_b are each individually time-ordered, as a real
# per-host or per-service log file would be, even though the SET of
# files is not globally ordered relative to each other.
with open(file_a, "w") as f:
f.write(json.dumps({"ts": "2025-01-01T00:00:01Z", "request_id": "req-1", "service": "C", "msg": "too_early"}) + "\n")
f.write(json.dumps({"ts": "2025-01-01T00:00:02Z", "request_id": "req-1", "service": "A", "msg": "start"}) + "\n")
f.write(json.dumps({"ts": "2025-01-01T00:00:09Z", "request_id": "req-2", "service": "A", "msg": "other_request"}) + "\n")
f.write("not valid json\n")
f.write(json.dumps({"ts": "2025-01-01T00:00:20Z", "request_id": "req-1", "service": "A", "msg": "too_late"}) + "\n")
with open(file_b, "w") as f:
f.write(json.dumps({"ts": "2025-01-01T00:00:05Z", "request_id": "req-1", "service": "B", "msg": "middle"}) + "\n")
start = _parse_ts("2025-01-01T00:00:02Z")
end = _parse_ts("2025-01-01T00:00:10Z")
for rec in extract_events([file_a, file_b], "req-1", start, end):
print(rec)
os.remove(file_a)
os.remove(file_b)
Worked example (executed output)
{'ts': '2025-01-01T00:00:02Z', 'request_id': 'req-1', 'service': 'A', 'msg': 'start'}
{'ts': '2025-01-01T00:00:05Z', 'request_id': 'req-1', 'service': 'B', 'msg': 'middle'}
file_a and file_b are individually time-ordered (as a real append-only log file would be), but the two files are not ordered relative to each other, and file_a even has an out-of-range line, a wrong-request-id line, and a malformed line mixed in. The output above still comes out correctly filtered and in chronological order across both files.
Key points
- Memory usage is
O(number of files), notO(file size)orO(number of matches): at any moment, the heap holds at most one buffered record per file, since each file is its own generator that only produces its next matching record when asked. - The k-way merge relies on one precondition worth stating explicitly: each individual file must already be time-ordered internally. That's a safe assumption for a normal append-only application log, but it would need to be checked (or the approach would need to change) for a log source that writes out of order within a single file.
extract_eventsis itself a generator (ityields rather than returning a list), so a caller can start consuming matching events immediately and stop early if it only needs the first few, rather than waiting for the entire multi-file scan to finish.
Complexity
Let N be the total number of matching events across all files and k be the number of files. Each heap push/pop is O(log k), and there are O(N) of them (one per yielded event, plus refills), so total time is O(N log k). Space is O(k) for the heap itself, plus the fixed per-line buffer each open file uses while being read, which is independent of file size.
Edge cases
- Malformed JSON lines: skipped rather than raising, so one corrupt line doesn't abort the entire scan (shown above:
file_a's "not valid json" line is silently passed over). - A file with no matches at all: its generator is simply exhausted immediately and it drops out of the heap; the merge continues correctly with the remaining files.
- Ties on identical timestamps across files: the heap comparison falls through to the file index as a tiebreaker, so results are still deterministic (files earlier in the input list sort first on an exact tie) rather than raising a comparison error on the underlying dict.
- A file that isn't actually time-ordered internally: this breaks the merge's chronological guarantee silently (each file's own stream would emit an out-of-order record without the heap detecting it), which is worth flagging explicitly rather than assuming away.
Trade-offs & pitfalls
A simpler alternative, collect every match into a list and sort once at the end, is easier to write and is fine when you expect a bounded, small number of matches for one request_id (usually true; a single request rarely touches millions of log lines). The heap-based merge shown here is the more defensible answer for a "must stream, must not load fully into memory" prompt because it doesn't rely on that assumption: it stays memory-bounded even in the pathological case where one request_id matches a huge number of events, which the simpler collect-and-sort approach would not.
Unlock Full Question Bank
Get access to all 12 Log Analysis and Diagnostic Data Gathering interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.