Repository navigation
level: don't read a key name as a line's level - #38
reckless-sherixx wants to merge 3 commits into
Conversation
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.
There was a problem hiding this comment.
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.
mayankpande88
left a comment
There was a problem hiding this comment.
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="", becauseParseStructuredLogreturnsGuessLevel(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.
| if jl != nil { | ||
| msg.Level = GuessLevel(jl.Message) | ||
| } else if !p.parseJson { | ||
| if fields := decodeJsonObject(msg.Content); fields != nil { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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) { |
There was a problem hiding this comment.
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
jsonLogFromFieldsdoesn't read:{"type":"error","text":"payment declined"}.structuredFromJSONtreatstext/reason/erras message content, but the re-guess reads onlymsg/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.
There was a problem hiding this comment.
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.
| if structuredLevel != LevelUnknown { | ||
| msg.Level = structuredLevel | ||
| } | ||
| // A JSON line keeps its level in a level key. Without one, a level guessed |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| msg.Level = GuessLevel(jl.Message) | ||
| } else if !p.parseJson { | ||
| if fields := decodeJsonObject(msg.Content); fields != nil { | ||
| msg.Level = GuessLevel(jsonLogFromFields(fields).Message) |
There was a problem hiding this comment.
Two points on this line:
- Hot path cost:
ParseStructuredLoghas already unmarshalled this line. This runs a secondjson.Decoderpass, thenjsonLogFromFields, 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:
decodeJsonObjectfollowed byjsonLogFromFieldsis whatParseJsonLog(json.go) already does.if jl := ParseJsonLog(msg.Content); jl != nil { ... }keeps one copy.
There was a problem hiding this comment.
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).
|
@mayankpande88 Thanks, I took the I checked plain-text formats that put brackets after the level word or quote a phrase that ends in one: |
Summary
A line with no level key but an
errorkey 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 aserror, and so did logfmt... status=200 error="".The cause was
GuessLevel, which read the key"error"as the word error.GuessLevelnow skips a key name: a quoted word directly followed by:("error":), or akey=valuetoken (error=""). Values still count, so{"type":"error"},{"msg":"error: db down"}andERROR[req=abc] ...keep their level. The change is inGuessLevel, so it covers single-line JSON, logfmt and multiline JSON alike.parseJsonmodes now read the same level keys.structuredFromJSONreads the keysjsonLogFromFieldsreads (@l,severity_text, numeric pino levels) before the olderpatternLevelKeys, so pino{"level":50}and Serilog{"@l":"Error"}areerrorwithparseJsonoff 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 aserror, as onmain.No API change. Each line is decoded once, as on
main.How to verify
go test -count=1 -run 'TestParserLevelNotFromKeyNames|TestGuessLevelSkipsKeys' ./....TestParserLevelNotFromKeyNamesruns 16 lines throughNewParserunder bothparseJsonmodes. They include the two health checks, logfmt and multilineerrorkeys, nested and non-level-key levels, and pino,50.0,@landseverity_textlevels. Onmain, theerror-key cases fail, and so do the numeric,@landseverity_textcases withparseJsonoff.What was run
go vet ./...,go build -mod=readonly ./...,go test -count=1 ./...pass.-racewas not run locally (no cgo on the dev box); CI runs it.GuessLevelwere compared on about 45 plain-text lines (glog/klog, nginx, apache, MySQL, Python logging, logback, dockerlevel=, UTF-8). They differ only on the intended key skips.