Prompt

how to parse json logs and stack traces

Technology / Observability1 observationLast seen Oct 28, 2026

Latest observation

Oct 28, 2026OpenAI APIWeb search: off

Parsing JSON logs and stack traces usually means two separate tasks:

  1. Extract the structured JSON fields from log lines.
  2. Detect and group stack traces that span multiple lines.

Here’s a practical way to approach both.


1) Parsing JSON logs

If each log line is valid JSON, parsing is straightforward.

Example JSON log

{"time":"2026-10-28T12:00:00Z","level":"error","msg":"failed request","user_id":123}

In Python

import json

line = '{"time":"2026-10-28T12:00:00Z","level":"error","msg":"failed request","user_id":123}'
record = json.loads(line)

print(record["level"])
print(record["msg"])

If logs are line-delimited JSON (NDJSON)

Read line by line:

import json

with open("app.log") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        try:
            record = json.loads(line)
            print(record)
        except json.JSONDecodeError:
            print("Not valid JSON:", line)

2) Parsing stack traces

Stack traces are often multi-line, so you usually need to:

  • recognize the start of an exception
  • collect all following lines until the next log entry

Example stack trace

2026-10-28 12:00:00 ERROR failed request
Traceback (most recent call last):
  File "app.py", line 10, in handle
    result = divide(a, b)
ZeroDivisionError: division by zero

Basic grouping strategy

A common approach:

  • A log entry starts when a line matches a timestamp/log prefix.
  • Any line that does not match that pattern is treated as a continuation of the previous entry.

3) Python example: parse mixed logs with multiline stack traces

import re

log_start = re.compile(r'^\d{4}-\d{2}-\d{2} ')  # adjust to your format

entries = []
current = []

with open("app.log") as f:
    for line in f:
        line = line.rstrip("\n")
        if log_start.match(line):
            if current:
                entries.append("\n".join(current))
            current = [line]
        else:
            current.append(line)

    if current:
        entries.append("\n".join(current))

for entry in entries:
    print("----")
    print(entry)

4) If logs are JSON but contain stack traces inside a field

Sometimes the JSON is one line, and the stack trace is stored in a field like "error" or "stack".

Example

{
  "time": "2026-10-28T12:00:00Z",
  "level": "error",
  "msg": "failed request",
  "error": "Traceback (most recent call last):\n  File \"app.py\", line 10, in handle\nZeroDivisionError: division by zero"
}

Parse it

import json

record = json.loads(line)
stack = record.get("error", "")
print(stack)

If the string contains escaped newlines (\n), JSON parsing will convert them into actual newline characters in Python.


5) Using regex for stack trace detection

For known stack trace patterns, regex helps identify:

  • Java exceptions
  • Python tracebacks
  • Go panics
  • Node.js errors

Python traceback start

^Traceback \(most recent call last\):

Java exception line

^Exception in thread ".*" .*

Node.js error

^Error: .*

6) Recommended approach in production

If you’re building a parser for real logs:

  • Prefer structured logging: emit JSON logs whenever possible.
  • Use a JSON parser for log lines.
  • Use stateful multiline parsing for stack traces.
  • Make the “start of log line” pattern configurable.
  • Add fallback handling for malformed lines.

7) Best practice: combine both

If your application can, emit logs like:

{"timestamp":"2026-10-28T12:00:00Z","level":"error","message":"request failed","exception":{"type":"ZeroDivisionError","message":"division by zero","stacktrace":"Traceback...\n..."}}

This is much easier to parse than plain text logs.


If you want, I can also give you:

  • a Python parser for JSON + multiline stack traces
  • a JavaScript/Node.js version
  • or help parse a specific sample log file you have.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.