fix: share mutex between a logger and its With() clones#210
Open
c-tonneslan wants to merge 1 commit into
Open
Conversation
With() was constructing a fresh *sync.RWMutex for every cloned logger, so the parent and any clones each held their own lock. Since they all share the same output io.Writer, concurrent writes from a parent and a clone weren't actually serialized — exactly the gotcha log/slog avoids by sharing the handler mutex among clones. Drop the new-mutex line so the value copy of l already gives the clone the parent's mutex pointer (and the existing assignment of fields, helpers, and styles still gets fresh copies). Closes charmbracelet#177. Signed-off-by: Charlie Tonneslan <cst0520@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #177.
`With()` was constructing a fresh `*sync.RWMutex` for every cloned logger, so the parent and any clones each held their own lock. They all share the same output `io.Writer` though, so concurrent writes from a parent and a clone weren't actually serialized — exactly the gotcha `log/slog` avoids by sharing the handler mutex among clones (see `commonHandler.clone()`).
The fix is to drop the new-mutex line. The value copy of `l` on the line above already gives the clone the parent's mutex pointer, and the existing assignments of `fields`, `helpers`, and `styles` still get fresh copies, so behavior is unchanged otherwise.
Test plan
```
go test -race ./...
```
Added `TestWithSharesMutex` asserting that one and two levels of `With()` produce loggers with the same `mu` pointer as the root. Existing `TestLogWithRaceCondition` and `TestRace` still pass with `-race`.