Prompt
How do I parse multiline stack traces and messy JSON logs into a searchable format?
Latest observation
To make multiline stack traces and messy JSON logs searchable, the main goal is to turn them into one event per log record with consistent fields.
1) Pick a structured target format
Common choices:
- JSON lines (NDJSON): one JSON object per line
- CSV: only if fields are very simple
- Log search indexes: Elasticsearch/OpenSearch, Splunk, Loki, Datadog, etc.
For searchability, JSON is usually best.
2) Handle multiline stack traces as a single event
Stack traces often span many lines, so you need a parser that groups them together.
Typical grouping rules
Treat a line as the start of a new event if it matches something like:
- timestamp at the beginning
- log level + timestamp
- known prefix format
Then any following lines that do not match the start pattern get appended to the previous event.
Example
Input:
2026-10-28 10:15:01 ERROR Failed to process request
java.lang.NullPointerException: Cannot read property
at com.example.Service.method(Service.java:42)
at com.example.Controller.handle(Controller.java:18)
2026-10-28 10:15:02 INFO Request completed
Parsed records:
{"timestamp":"2026-10-28 10:15:01","level":"ERROR","message":"Failed to process request\njava.lang.NullPointerException: Cannot read property\n at com.example.Service.method(Service.java:42)\n at com.example.Controller.handle(Controller.java:18)"}
{"timestamp":"2026-10-28 10:15:02","level":"INFO","message":"Request completed"}
3) Parse JSON logs safely
If your logs are “messy JSON,” the first step is to determine the failure mode:
Cases
- Valid JSON per line: easy, just parse line-by-line
- Pretty-printed JSON over multiple lines: need multiline grouping
- Mixed plain text + JSON: use conditional parsing
- Invalid JSON: sanitize or extract fields with regex before parsing
If the log is JSON-like but not valid
Examples of common issues:
- trailing commas
- single quotes instead of double quotes
- unescaped newlines
- non-JSON prefixes/suffixes
You may need preprocessing:
- remove prefixes like timestamps
- replace single quotes with double quotes carefully
- escape raw newlines inside string values
- strip trailing commas
4) Use a log parser pipeline
A practical approach is:
Step A: Detect record boundaries
Use multiline rules based on timestamp or known prefixes.
Step B: Try JSON parse
If the full record looks like JSON, parse it.
Step C: Fallback to text extraction
If JSON parsing fails, use regex or grok-like patterns to extract fields:
- timestamp
- level
- service
- request_id
- message
Step D: Normalize fields
Convert to a standard schema:
timestamplevelserviceloggermessagestack_tracetrace_iduser_id
5) Recommended tools
Depending on your stack:
Fluent Bit / Fluentd
Good for:
- multiline handling
- parsing JSON
- shipping to Elasticsearch/OpenSearch/Loki
Logstash
Good for:
- grok patterns
- multiline codec
- JSON parsing
- enrichment
Vector
Good for:
- fast parsing/transformation
- multiline support
- structured logging pipelines
Filebeat
Good for:
- multiline input handling
- JSON decoding
- shipping to Elasticsearch
Custom script
If you have a one-time migration, Python is often easiest.
6) Example Python approach
A simple strategy is:
- read lines
- decide whether a line starts a new event
- join continuation lines
- parse JSON if possible
Pseudo-example:
import json
import re
start_re = re.compile(r'^\d{4}-\d{2}-\d{2} ')
events = []
current = []
with open("app.log") as f:
for line in f:
if start_re.match(line) and current:
events.append("".join(current))
current = [line]
else:
current.append(line)
if current:
events.append("".join(current))
parsed = []
for event in events:
event = event.strip()
try:
parsed.append(json.loads(event))
except json.JSONDecodeError:
parsed.append({"message": event})
7) Make it searchable
Once parsed, index fields separately:
- exact-match fields:
level,service,trace_id - full-text fields:
message,stack_trace
This lets you search:
- all
ERRORlogs - all logs for a specific request
- logs containing
NullPointerException - stack traces from a specific service
8) Best practices
- Prefer structured logging at source if possible
- Include timestamps, levels, request IDs, and trace IDs
- Keep stack traces in one field
- Use a consistent schema across services
- Avoid embedding giant blobs in one text field if you need faceted search
9) Practical recommendation
If you’re starting from scratch:
- emit one JSON object per log event
- keep stack traces as a single escaped string field
- ship with a parser that supports multiline handling
- index into a search system with both structured and full-text fields
If you want, I can give you:
- a Logstash/Fluent Bit/Vector config, or
- a Python script to parse your specific log format.