Skip to content

fix: share mutex between a logger and its With() clones#210

Open
c-tonneslan wants to merge 1 commit into
charmbracelet:mainfrom
c-tonneslan:fix/share-mutex-with-clones
Open

fix: share mutex between a logger and its With() clones#210
c-tonneslan wants to merge 1 commit into
charmbracelet:mainfrom
c-tonneslan:fix/share-mutex-with-clones

Conversation

@c-tonneslan

Copy link
Copy Markdown

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`.

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>
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.

Output io.Writer concurrency gotcha compared to stdlib

1 participant