Skip to content

level: don't read a key name as a line's level - #38

Open
reckless-sherixx wants to merge 3 commits into
mainfrom
fix/json-level-guess-from-key-names
Open

reckless-sherixx wants to merge 3 commits into
mainfrom
fix/json-level-guess-from-key-names

Conversation

@reckless-sherixx

@reckless-sherixx reckless-sherixx commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A line with no level key but an error key was emitted as an error. Go access logs (Echo, Gin) are the common case: every {"method":"GET","uri":"/healthz","status":200,"error":""} health check came out as error, and so did logfmt ... status=200 error="".

The cause was GuessLevel, which read the key "error" as the word error.

  • GuessLevel now skips a key name: a quoted word directly followed by : ("error":), or a key=value token (error=""). Values still count, so {"type":"error"}, {"msg":"error: db down"} and ERROR[req=abc] ... keep their level. The change is in GuessLevel, so it covers single-line JSON, logfmt and multiline JSON alike.
  • Both parseJson modes now read the same level keys. structuredFromJSON reads the keys jsonLogFromFields reads (@l, severity_text, numeric pino levels) before the older patternLevelKeys, so pino {"level":50} and Serilog {"@l":"Error"} are error with parseJson off too. A numeric level is accepted however it is written (50, 50.0, 5e1).

Trade-off: in plain text, a quoted word followed by a colon ("ERROR": none) now reads as a key, not a level. A dotted logfmt key (error.code=5) is still read as error, as on main.

No API change. Each line is decoded once, as on main.

How to verify

go test -count=1 -run 'TestParserLevelNotFromKeyNames|TestGuessLevelSkipsKeys' ./.... TestParserLevelNotFromKeyNames runs 16 lines through NewParser under both parseJson modes. They include the two health checks, logfmt and multiline error keys, nested and non-level-key levels, and pino, 50.0, @l and severity_text levels. On main, the error-key cases fail, and so do the numeric, @l and severity_text cases with parseJson off.

What was run
  • go vet ./..., go build -mod=readonly ./..., go test -count=1 ./... pass. -race was not run locally (no cgo on the dev box); CI runs it.
  • The old and new GuessLevel were compared on about 45 plain-text lines (glog/klog, nginx, apache, MySQL, Python logging, logback, docker level=, UTF-8). They differ only on the intended key skips.

A container log line has no level from its source, so the line collector
guesses one from the raw text. For a JSON line that has no level key, that
guess came from the key names: an access log's {"status":200,"error":""}
read as an error, because "error" is a key. JSON parsing kept the guess,
since it found no level key to override it with.

The collector now records that a level was guessed. When the line turns
out to be a JSON object without a level key, the parser guesses again from
the JSON message field alone ({"msg":"error: db down"} is still an error),
or leaves the level unknown. A level the source reports, such as a journald
priority, is kept. Both parseJson modes behave the same.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a levelGuessed flag to track whether a log level was guessed from the content. In parser.go, this flag is used to refine the log level for JSON lines that lack an explicit level key, preventing false-positive level guesses from key names (such as "error"). A performance optimization was suggested to avoid the expensive JSON decoding in parser.go when msg.Level is already LevelUnknown.

Comment thread parser.go Resolved

@mayankpande88 mayankpande88 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran sample lines through NewParser on this head. The fix works for the access-log case, but it turns some lines that used to be error into unknown, and the two parseJson modes still give different levels. Details are inline.

One more point, outside the diff (level.go, GuessLevel): the root cause is that GuessLevel reads a key name ("error":, error=) as a level word, and this PR patches only single-line JSON in Parser.inc. These lines are still error in both modes:

  • logfmt: method=GET uri=/healthz status=200 error="", because ParseStructuredLog returns GuessLevel(line) as its level
  • multiline JSON: {"method":"GET","status":200,"error":""} followed by a continuation line

If GuessLevel skipped a token followed by ": or = (a key, not a value), every format would be covered, and the re-guess block here might not be needed.

Comment thread parser.go Outdated
if jl != nil {
msg.Level = GuessLevel(jl.Message)
} else if !p.parseJson {
if fields := decodeJsonObject(msg.Content); fields != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With parseJson=false, this branch throws away the level that jsonLogFromFields already parsed. It checks only structuredLevel, which comes from the narrower patternLevelKeys list (string values only). jsonLevelKeys also covers @l, severity_text and numeric levels.

These lines were error before this PR and are unknown with parseJson=false (they stay error with parseJson=true):

  • Serilog CLEF: {"@t":"...","@l":"Error","@mt":"Payment {Id} declined"}
  • OTel: {"severity_text":"ERROR","body":"payment declined"}

Suggest using jl.Level when it is known and falling back to guessing from the message only otherwise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f72585f. The re-guess block is gone, and the level now comes from one place: structuredFromJSON reads the jsonLevelKeys first (strings and numbers, chosen the same way jsonLogFromFields chooses), then patternLevelKeys. The CLEF and OTel lines are error in both modes. Both are test cases in TestParserLevelNotFromKeyNames, which runs every case under both parseJson modes.

Comment thread parser.go Outdated
// A JSON line keeps its level in a level key. Without one, a level guessed
// from the raw line came from its key names ({"error":""} reads as an
// error), so it is guessed again from the message alone, or left unknown.
if msg.levelGuessed && structuredLevel == LevelUnknown && (jl == nil || jl.Level == LevelUnknown) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This replaces the raw-line guess with a guess from the message alone, so any line whose level isn't in a recognised level key now becomes unknown, in both modes. Lines that were error before this PR:

  • nested level: {"log":{"level":"error"},"message":"payment declined"}
  • level in a non-level key, message in a key jsonLogFromFields doesn't read: {"type":"error","text":"payment declined"}. structuredFromJSON treats text/reason/err as message content, but the re-guess reads only msg/message/@m/@mt/body/log.

Unknown-level lines return early with an empty hash, so these lines also drop out of error counts and pattern extraction. The trade-off in the description covers only the "error":"" value case.

Smaller point: this block and the existing if jl != nil { if jl.Level != LevelUnknown { ... } } block below now branch on the same state, so the level is set by three overwrites in a row (structuredLevel, re-guess, jl.Level) and the result depends on their order. Resolving the level in one place would make cases like the ones above easier to see.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f72585f, along the lines of your review comment: GuessLevel now skips a key name, and the re-guess block and levelGuessed are removed. The nested-level and type/text lines are error again, and both are test cases now.

On the smaller point: the level is set in one place now. structuredLevel, when known, replaces the raw guess. It already holds what jl.Level would give, so the separate jl.Level overwrite is removed.

One side effect: a line whose only level word is past GuessLevel's 7-field reach (json.dumps spacing, "msg": "error: ..." as the 8th field) is unknown again in both modes, as on main. I dropped the test case that covered the re-guess for it.

Comment thread parser.go Outdated
if structuredLevel != LevelUnknown {
msg.Level = structuredLevel
}
// A JSON line keeps its level in a level key. Without one, a level guessed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The modes still disagree because they read levels from different key sets: structuredFromJSON uses patternLevelKeys (strings only), and jsonLogFromFields uses jsonLevelKeys (including numbers). For example, pino {"level":50,"msg":"payment declined"} is error with parseJson=true and unknown with parseJson=false.

The new test has no numeric, @l or severity_text case. Adding those would catch this and the regression on L253.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f72585f. structuredFromJSON reads the jsonLevelKeys with jsonLevelFromValue before patternLevelKeys, so pino {"level":50,...} is error in both modes. jsonLevelFromValue also takes the float64 that json.Unmarshal produces, and a numeric level is accepted however it is written (50, 50.0, 5e1). The test now has numeric, 50.0, @l and severity_text cases, all run under both modes.

Comment thread parser.go Outdated
msg.Level = GuessLevel(jl.Message)
} else if !p.parseJson {
if fields := decodeJsonObject(msg.Content); fields != nil {
msg.Level = GuessLevel(jsonLogFromFields(fields).Message)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two points on this line:

  • Hot path cost: ParseStructuredLog has already unmarshalled this line. This runs a second json.Decoder pass, then jsonLogFromFields, which builds an attributes map of up to 100 entries (recursing into nested objects) only to read one string. On high-volume access logs, the target case, that roughly doubles JSON CPU and allocations per line. Returning the message value from the first decode would avoid it.
  • Reuse: decodeJsonObject followed by jsonLogFromFields is what ParseJsonLog (json.go) already does. if jl := ParseJsonLog(msg.Content); jl != nil { ... } keeps one copy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in f72585f: the second decode went away with the re-guess block, so each line is decoded once again, as on main.

…e key set

GuessLevel now skips a key, a quoted word followed by a colon ("error":)
or a word=value pair (error=""), instead of reading it as a level word.
That fixes every format, not just single-line JSON: logfmt and multiline
JSON lines with an empty error field are no longer errors.

This replaces the re-guess from the JSON message field and the
levelGuessed flag, which turned lines whose level sat outside a level
key into unknown and decoded the line a second time.

structuredFromJSON reads the level from the keys jsonLogFromFields
reads (@l, severity_text, numeric levels) before patternLevelKeys, so
a line gets the same level with and without parseJson. A numeric level
is accepted however it is written (50, 50.0, 5e1).
@reckless-sherixx

Copy link
Copy Markdown
Contributor Author

@mayankpande88 Thanks, I took the GuessLevel route you suggested, in f72585f. A quoted word directly followed by : ("error":) or a key=value token (error="") is no longer read as a level word. That covers logfmt and multiline JSON as well, and the re-guess block is gone.

I checked plain-text formats that put brackets after the level word or quote a phrase that ends in one: ERROR[req=abc] ..., WARN(user=bob) ... and Failed "connection error": timeout all keep their level, and there are unit tests for each in TestGuessLevelSkipsKeys. Two things are left as they are. A quoted word followed by a colon in plain text ("ERROR": none) now reads as a key. A dotted logfmt key (error.code=5) is still read as error, the same as on main.

@reckless-sherixx reckless-sherixx changed the title parser: don't read a JSON line's key names as its level level: don't read a key name as a line's level Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants