Skip to content

Conversation

arthurpitman
Copy link
Contributor

@arthurpitman arthurpitman commented Jun 6, 2025

Why this PR?

We experienced a race condition being detected in a test logging to a bytes.Buffer. Although the problem doesn't occur when logging to os.Stderr, presumably because this is synchronized, it is reproducible when a logger uses a cloned handler.

What has changed?

Based on https://github.com/golang/example/blob/8b405629c4a5215871be932097e099c05ec5cb2e/slog-handler-guide/README.md#concurrency-safety, synchronization in handler is changed to share a mutex among all clones, similar to slog.commonHandler https://cs.opensource.google/go/go/+/refs/tags/go1.24.3:src/log/slog/handler.go;l=197.

How is it tested?

An explicit test triggering a race condition is added: TestClonedHandlersSynchronizeWriter.

How does it affect users?

There should be no effect on users.

@arthurpitman arthurpitman changed the title Fix/: Cloned handlers use same mutex Fix: Cloned handlers should use same mutex Jun 6, 2025
@arthurpitman arthurpitman marked this pull request as draft June 6, 2025 08:49
@arthurpitman arthurpitman force-pushed the fix/cloned-handlers-use-same-mutex branch from b39b74b to 901d028 Compare June 6, 2025 08:57
All handlers cloned from the handler attached to a logger should synchronize writer writes. This allows the logger to be used from multiple go routines.

Here we add a test writing to a `bytes.Buffer` which itself is in not synchronized to expose the problem.
Drawing on the information in https://github.com/golang/example/blob/8b405629c4a5215871be932097e099c05ec5cb2e/slog-handler-guide/README.md#concurrency-safety, the handler is adapted to store a pointer to a mutex so that it and all of its clones synchronize with each other.
@arthurpitman arthurpitman force-pushed the fix/cloned-handlers-use-same-mutex branch from 901d028 to 925ec80 Compare June 6, 2025 08:59
@arthurpitman arthurpitman marked this pull request as ready for review June 6, 2025 09:28
@lmittmann lmittmann changed the title Fix: Cloned handlers should use same mutex Fix cloned handlers to use same mutex Jun 7, 2025
@lmittmann lmittmann merged commit 401cb97 into lmittmann:main Jun 7, 2025
2 checks passed
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