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.
You're investigating an incident from three days ago, but journalctl on the affected host only shows the last several hours of logs. Walk through what could explain that gap (journald's own settings, disk pressure, a reboot) and how you'd confirm on the box which one actually happened here.
Sample Answer
Direct answer
journalctl reads from journald (the logging component of systemd, the process manager on most modern Linux distributions), and there are exactly three independent reasons three days of history could be missing: the journal was never configured to survive a reboot, journald ran out of its allotted disk budget and quietly deleted the oldest entries, or the host actually rebooted recently and there's no separate storage retaining pre-reboot logs. Each has a distinct, checkable fingerprint on the box, so you don't have to guess.
Structured elaboration
1. journald's own storage settings. Storage= in /etc/systemd/journald.conf (plus any drop-in files under /etc/systemd/journald.conf.d/*.conf, which override or extend it) controls where logs live:
Storage=volatilekeeps logs only in/run/log/journal, which is backed by RAM (tmpfs) and is wiped on every reboot, by design.Storage=auto(the common default) uses persistent storage at/var/log/journalif that directory already exists, otherwise silently falls back to volatile storage. A host where nobody ever created that directory will look like it's misconfigured, when it's actually behaving exactly as documented.- Confirm:
ls -ld /var/log/journal(does the persistent directory exist at all?) and check the effectiveStorage=value in the config files. If it's missing or set tovolatile, that alone explains a hard cutoff at the last reboot, regardless of anything else.
2. Disk pressure. journald keeps its own disk-usage budget even without an explicit SystemMaxUse= set; on a host with little free space, that budget can be reached fast, and journald vacuums (deletes) the oldest journal files to stay under it, which looks exactly like "old logs are just gone."
- Confirm:
journalctl --disk-usageshows how much space the journal itself is currently using.df -h /var/log/journal(or wherever persistent storage lives) shows how much free space the filesystem actually has. If free space is tight, or--disk-usageshows a size suspiciously close to a configuredSystemMaxUse=/SystemKeepFree=, disk pressure is a strong candidate. Also checkjournalctl --verify, which reports per-file integrity (PASS/FAIL); a corrupted file from a prior disk-full event can also make journald treat older files as unusable.
3. A reboot. If persistent storage genuinely is enabled and there's no disk pressure, but three days of logs are still gone, the most direct explanation is that this host rebooted and, on top of that, there's no journal file spanning the boot before the gap (e.g. it was rotated away by MaxFileSec=/MaxRetentionSec=, independent of disk pressure).
- Confirm:
journalctl --list-bootslists every boot journald has a record of, each with a boot ID and its first/last timestamp. If there's no boot entry covering three days ago at all, either the host rebooted since then and that boot's files were later rotated away on age (MaxFileSec=/MaxRetentionSec=), or, combined with finding #1 above, the logs from that boot were never persisted past the next reboot in the first place.
Worked example
A realistic diagnostic sequence on the affected host, in order of cost (cheapest checks first):
# 1. Is persistent storage even enabled?
ls -ld /var/log/journal
grep -R "^Storage=" /etc/systemd/journald.conf /etc/systemd/journald.conf.d/ 2>/dev/null
# 2. Is journald under disk pressure right now, or was it recently?
journalctl --disk-usage
df -h /var/log/journal
# 3. Did the host actually reboot, and does a boot from 3+ days ago even
# have a journal entry?
journalctl --list-boots
# 4. Rule out silent corruption from a prior disk-full event.
journalctl --verify
Reading these in combination narrows it down: Storage=volatile (or a missing /var/log/journal) plus a boot in --list-boots around the time the gap starts points squarely at cause #1. A persistent Storage=persistent, an empty or tight --disk-usage result relative to free disk space, plus no unusual boot around the gap points at cause #2. A boot entry that starts right where the visible logs start, with no corresponding older boot listed, points at cause #3 (possibly compounded by #1 if that older boot's logs were never persisted at all).
Trade-offs & pitfalls
- These three causes aren't mutually exclusive: a host with
Storage=autoand no/var/log/journaldirectory that also just rebooted will show the same symptom as one purely driven by disk pressure, so check all three rather than stopping at the first plausible-looking one. journalctl --list-bootsonly tells you what journald itself still has a record of; if the relevant boot's files were already rotated away (age- or size-based), the boot won't appear at all, which can look identical to "this host has never had persistent logging enabled."- If the answer turns out to be "logs genuinely don't exist anywhere for that period," the actionable fix isn't just enabling
Storage=persistentgoing forward, it's also deciding whether you need a remote log shipper (forwarding to a central store) so a single host's local retention policy is never the only copy of an incident's evidence.
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.
Your log-processing pipeline needs to keep up with roughly 200k JSON log lines per second per host, and profiling shows the parsing step itself is the bottleneck, not disk or network I/O. Walk through how you'd diagnose where the time is actually going, what class of tooling you'd consider moving to if a scripting-language parser can't keep up, and how you'd benchmark candidate approaches before committing to a rewrite.
Sample Answer
Direct answer
Before touching the language or the parser, profile the parsing step itself with a sampling profiler to find out whether the cost is really JSON decoding, or something adjacent like object/dict allocation, string encoding conversions, or field extraction logic sitting next to the parse call. Only after that's confirmed as the actual hot path is a rewrite (to a compiled language, or to a SIMD-accelerated JSON parser) worth considering, and even then, the cheapest fix is often to see whether the shell-tooling tier (grep/awk/sed) can filter or pre-shape the data so less JSON ever needs full parsing at all.
Structured elaboration
1. Diagnose where the time is actually going. "Parsing is the bottleneck" from a coarse profile (CPU is pegged, I/O is idle) still leaves several distinct possibilities:
- Use a sampling profiler (
py-spyfor Python,pproffor Go,perfat the OS level) to get a flame graph (a visualization showing which function calls consumed the most CPU time, stacked by call depth, so the widest bars are the hottest code paths) and see whether time is in the actual decode call (e.g.json.loads) or in what your code does with the result (building dict-of-dicts, converting to your internal schema, string encode/decode churn). - Check allocation behavior separately from CPU time (Python's
tracemalloc, Go'spprof -alloc_objects): a lot of "parsing is slow" turns out to be garbage-collector pressure from allocating a new dict and set of strings per line, not the byte-level scanning itself. - Isolate parsing from I/O properly: feed the parser from an in-memory buffer or
/dev/shmfor the profiling run so disk/network jitter can't leak into the measurement, confirming the earlier finding that I/O isn't the bottleneck.
2. The cheaper step before a rewrite. A full language rewrite is a multi-week investment with real risk; before reaching for it, check whether the shell-tooling tier can do enough of the job:
grep/mawk/sedare compiled C programs with tight, allocation-light loops. If most lines can be filtered out (e.g. you only care aboutlevel=ERRORlines, or only a handful of fields) before they ever reach a JSON parser, agrep-then-parse pipeline can cut the number of lines that pay the full JSON-decode cost by an order of magnitude for free.- If you need real field extraction rather than just filtering, tools like
jqor aawk-based fixed-position extractor can pull specific fields without a general-purpose JSON parse, at the cost of being fragile to schema changes. - This step matters because it changes the actual problem: "parse 200k lines/sec" might become "parse the 20k lines/sec that survived filtering," which a scripting-language parser may already handle fine, no rewrite needed at all.
3. If a rewrite is still justified, what class of tooling. Once you've confirmed the decode itself (not allocation, not I/O, not unnecessary work) is the bottleneck, and pre-filtering doesn't reduce the problem enough, the realistic options are:
- A compiled, garbage-collected language (Go): a large step up in throughput with a manageable operational profile; still has GC pauses under sustained allocation, which pooling (reusing buffers/structs via a pool instead of allocating fresh ones per line) mitigates.
- A systems language with manual memory control (Rust): highest achievable throughput and predictable latency (no GC pauses), at the cost of a steeper team ramp-up.
- A SIMD-accelerated JSON parser (e.g. simdjson and its bindings): uses CPU vector instructions (single instruction, multiple data, meaning one instruction processes several bytes in parallel) to scan JSON far faster than a byte-at-a-time parser; typically wrapped in a small Go or Rust service since simdjson itself is a C++ library.
The right choice depends on how much of the rest of your pipeline is already in that language: a Go rewrite that reuses your existing Go services is a smaller organizational lift than introducing Rust or C++ purely for this one hot path.
4. Benchmarking before committing. A microbenchmark that doesn't resemble production traffic will mislead you:
- Build the benchmark corpus from real captured log samples, not synthetic data, including your actual field cardinality, nesting depth, and line-length distribution, not just an average-case line repeated a million times.
- Measure more than one thing: lines/sec throughput, but also p50/p95/p99 latency per line (a parser that's fast on average but spikes on deeply-nested lines will still cause tail-latency problems downstream), and memory allocation rate.
- Run sustained (multi-minute) trials, not single-shot timings; JIT (just-in-time compilation, where the runtime compiles and speeds up hot code paths only after a warm-up period)/GC-based runtimes behave very differently warm vs. cold.
- Shadow the candidate against real production traffic (processing a copy of the live stream without acting on the output) before cutting over, so the decision is validated against real, current data shapes rather than the benchmark corpus alone.
I'm not going to state specific throughput numbers here (lines/sec, milliseconds) because they're entirely dependent on your hardware, log shapes, and even background load at benchmark time; the value is in the benchmark harness's shape (representative data, percentile tracking, sustained runs), which is what you'd actually run to get numbers you can trust for your own environment. A benchmark skeleton looks like this:
import time, statistics
def benchmark(parse_fn, corpus, warmup=5000):
for line in corpus[:warmup]:
parse_fn(line) # warm up JIT/caches, discard timing
latencies = []
start = time.perf_counter()
for line in corpus[warmup:]:
t0 = time.perf_counter()
parse_fn(line)
latencies.append(time.perf_counter() - t0)
total = time.perf_counter() - start
return {
"lines_per_sec": len(corpus[warmup:]) / total,
"p50_us": statistics.median(latencies) * 1e6,
"p99_us": sorted(latencies)[int(len(latencies) * 0.99)] * 1e6,
}
Run this on your own captured corpus against each candidate parser to get numbers specific to your hardware and data, that comparison is the deliverable, not any single absolute number.
Trade-offs & pitfalls
- The most common mistake here is skipping straight to "rewrite in Rust" because 200k/sec sounds intimidating, without ever confirming that decode itself (not allocation, not unnecessary downstream work, not I/O) is actually the cost. That can burn weeks rewriting the wrong bottleneck.
- simdjson-class parsers are fastest at raw scanning but usually parse into a DOM-like view (a tree of in-memory objects you then navigate to pull out fields, the same idea as the DOM a browser builds from parsed HTML) you then have to extract fields from; if your real cost is field extraction and schema mapping, a faster raw parser alone won't fix it.
- A rewrite that's faster in isolation but harder to operate (a language your team doesn't run in production elsewhere) can be a net loss even if the benchmark numbers look good; factor operational cost into the decision, not just throughput.
Compare different approaches to log aggregation and retention for forensic investigations at enterprise scale: self-hosted ELK, managed cloud logging, and cold object-store. Discuss trade-offs in cost, query latency, retention, compliance, and operational burden for each approach.
Sample Answer
Direct answer
Self-hosted ELK (Elasticsearch, Logstash, Kibana, the classic open-source log-search stack), managed cloud logging, and cold object storage sit at three different points on the same cost-versus-query-latency curve for forensic retention: cheaper, colder, and slower to query as you move from ELK toward object storage, with retention economics and operational burden moving in the opposite direction.
Structured elaboration
| Dimension | Self-hosted ELK | Managed cloud logging | Cold object storage (e.g. an S3-style bucket) |
|---|---|---|---|
| Cost | High fixed cost: infrastructure plus the ops time to run it | Usage-based (ingest and retention volume); shifts cost from headcount to a recurring bill | Lowest cost per gigabyte by a wide margin; the cheapest option for years of retention |
| Query latency | Fast (sub-second to seconds) if sized and indexed correctly | Fast for recent data; heavy ad hoc queries may be rate-limited or cost extra | Slow; minutes, not seconds, unless you've pre-indexed or partitioned the data, since it's not a search engine |
| Retention | Gets expensive fast at scale, since indexed storage costs far more than raw storage | Vendor-tiered; long retention is available but priced accordingly | Cheap and practical for multi-year retention; built for exactly this |
| Compliance | Full control, but you implement immutability and access controls yourself | Strong built-in controls, but possible data-residency constraints depending on vendor regions | Good: object-lock/WORM (write-once-read-many) style immutability features exist, but you still design the access-control and integrity story |
| Operational burden | High: cluster sizing, upgrades, index lifecycle management, backups | Low: the vendor runs the platform; you manage ingestion and IAM (identity and access management) policy | Low for storage itself, moderate for building a reliable ingestion and later query path |
Worked example
A forensic investigation needs to pull specific evidence from 18 months ago. Against cold object storage alone with no pre-built index, that query might take many minutes to hours, since you're effectively scanning partitioned files rather than hitting a search index; the same query against a live ELK cluster holding that same 18 months of data would return in seconds, but only if the team was willing to pay to keep 18 months indexed and hot the whole time, which for most teams is the expensive part of this trade-off, not the storage itself.
Trade-offs & pitfalls
The practical answer for most teams doing forensic investigations at enterprise scale isn't picking exactly one of these three, it's a tiered pattern: keep a shorter, indexed hot/warm window (days to a few weeks) in ELK or a managed logging product for fast, ad hoc investigation, then move older data into cheap, partitioned cold object storage for long-term compliance retention, paired with a serverless or batch query layer for the rare occasions you actually need to search far back. The pitfall to watch for is treating cold storage as a drop-in replacement for a search index: teams sometimes archive to object storage to save cost and only discover during an actual forensic investigation, under time pressure, that "search 18 months of raw files" takes far longer than anyone budgeted for, because nobody tested the retrieval path until it was needed for real.
Write a Logstash/ELK grok pattern (or equivalent) for Nginx 'combined' access logs to extract client_ip, timestamp, method, path, protocol, status, bytes_sent, and user_agent. Explain how you'd handle query strings in path, percent-encoding, and very long user-agent strings to avoid mapping explosion in Elasticsearch.
Sample Answer
Direct answer
Grok is the pattern-matching DSL (domain-specific language, a small purpose-built syntax rather than a general programming language) that Logstash's grok filter uses to name regex fragments and compose them, so you write field names instead of raw regex. The Logstash grok pattern below is illustrative configuration (not something this environment can execute against a real Logstash pipeline); the field boundaries it encodes are verified separately with an equivalent, executed Python regex against a real nginx combined log line.
Approach
Logstash grok pattern
%{IPORHOST:client_ip} - %{USER:ident} \[%{HTTPDATE:timestamp}\] "%{WORD:method} %{DATA:path} %{DATA:protocol}" %{NUMBER:status} %{NUMBER:bytes_sent} "%{DATA:referrer}" "%{DATA:user_agent}"
Each %{PATTERN:field_name} is a named, reusable regex fragment from grok's built-in pattern library: %{IPORHOST} matches an IP address or hostname, %{USER} matches a username token, %{HTTPDATE} matches Apache's bracketed date format, %{WORD} matches one alphabetic token, and %{NUMBER} matches a numeric string, each expanding to a pre-built regex fragment so you don't have to write it by hand. %{DATA} is grok's non-greedy "anything" pattern, used here for path, protocol, referrer, and user_agent because those fields can contain almost any character. Note that grok's own built-in COMBINEDAPACHELOG pattern names the trailing HTTP/1.1 token httpversion and only captures the version number, not the scheme; since the question asks specifically for a field named protocol, this pattern captures the whole HTTP/1.1 token (scheme and version together) under that name instead, which is the more literal reading of "protocol."
Verifying the field boundaries (executed)
import re
# Same field boundaries as the grok pattern
# %{IPORHOST:client_ip} - %{USER:ident} \[%{HTTPDATE:timestamp}\]
# "%{WORD:method} %{DATA:path} %{DATA:protocol}"
# %{NUMBER:status} %{NUMBER:bytes_sent} "%{DATA:referrer}" "%{DATA:user_agent}"
PATTERN = re.compile(
r'^(?P<client_ip>\S+) - (?P<ident>\S+) '
r'\[(?P<timestamp>[^\]]+)\] '
r'"(?P<method>[A-Z]+) (?P<path>\S+) (?P<protocol>[A-Z]+/[\d.]+)" '
r'(?P<status>\d+) (?P<bytes_sent>\d+|-) '
r'"(?P<referrer>[^"]*)" '
r'"(?P<user_agent>[^"]*)"$'
)
line = ('203.0.113.5 - - [10/Oct/2024:13:55:36 -0700] '
'"GET /search?q=test%20query HTTP/1.1" 200 5231 '
'"https://example.com/" '
'"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"')
m = PATTERN.match(line)
if m:
for k, v in m.groupdict().items():
print(f"{k}: {v}")
else:
print("no match")
Worked example (executed output)
client_ip: 203.0.113.5
ident: -
timestamp: 10/Oct/2024:13:55:36 -0700
method: GET
path: /search?q=test%20query
protocol: HTTP/1.1
status: 200
bytes_sent: 5231
referrer: https://example.com/
user_agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
Key points
- Query strings in the path:
%{DATA:path}is non-greedy, so it stops at the first space rather than trying to consume the rest of the line; a query string like?q=test%20querystays part of thepathfield intact, exactly as shown above (/search?q=test%20query). If you needpathandqueryas separate fields, add adissectormutatestep after the grok match to split on the first?. - Percent-encoding: neither grok nor this regex decodes
%20into a space; that's expected; percent-encoding is part of the raw URL and decoding it is a separate, deliberate step (only do it if you actually need the decoded form for display or analysis, since the encoded form is what the server actually received). - Very long user agents and mapping explosion: in Elasticsearch, a
textor default-mappedkeywordfield indexes every unique value it sees; browser and bot user-agent strings are extremely high-cardinality (having a very large number of distinct values) and some are very long, which can blow up index size and even hit Elasticsearch's field-length limits. The practical mitigations are: mapuser_agentaskeywordwithignore_aboveset (so overlong values are stored but not indexed for aggregation), truncate the field before indexing if you only need it for display, and, if you need to group by user agent at all, index a hash of the full string instead of the raw string for aggregation purposes. - Naming
protocolvs. a library's default field name: this is a small but real pitfall in its own right. A team pulling in a stockCOMBINEDAPACHELOG-style pattern will gethttpversion, notprotocol, and a downstream query or dashboard written against "protocol" will silently return nothing until someone notices the field doesn't exist. When a spec (a question, a ticket, a schema doc) names a field explicitly, match that name exactly, or add an explicit rename/alias step, rather than assuming a library's default naming is close enough.
Trade-offs & pitfalls
The main pitfall with grok specifically is that a malformed line (one that doesn't match the pattern at all) produces no match and typically gets tagged as a parse failure rather than partially parsed; a production pipeline needs a fallback path for those lines rather than silently dropping them. The other common mistake is treating query strings as low-cardinality: a path with a highly variable query string (a session token, a timestamp) indexed as a single keyword field will itself cause the same kind of cardinality blowup as an unbounded user-agent field, so the same truncate-or-split discipline usually needs to apply to path as well, not just to user_agent.
Unlock Full Question Bank
Get access to all 28 Log Analysis and Diagnostic Data Gathering interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.