Skip to content

Share level pointer so child loggers inherit parent level changes#209

Open
c-tonneslan wants to merge 1 commit into
charmbracelet:mainfrom
c-tonneslan:fix/wrapped-logger-level-inheritance
Open

Share level pointer so child loggers inherit parent level changes#209
c-tonneslan wants to merge 1 commit into
charmbracelet:mainfrom
c-tonneslan:fix/wrapped-logger-level-inheritance

Conversation

@c-tonneslan

Copy link
Copy Markdown

Fixes #184.

When With() copies the logger struct, the level field was copied by value, so the child got its own independent level. Calling SetLevel on the parent after creating a child had no effect on the child.

The fix is straightforward: change level from int64 to *int64. Since parent and child now share the same pointer, a SetLevel call on either one is immediately visible to both. All the atomic reads/writes already go through atomic.LoadInt64/atomic.StoreInt64, they just don't need the address-of operator anymore. Also dropped the mutex from GetLevel and SetLevel since the atomics are sufficient.

Added a regression test in logger_test.go (TestWithInheritsParentLevel) that verifies the child sees the parent's level changes in both directions.

To test: run go test -run TestWithInheritsParentLevel ./...

When With() copies the logger struct, the level field was copied by
value, so the child got its own independent level. That meant calling
SetLevel on the parent after creating a child had no effect on the child.

Change level from int64 to *int64 so parent and child share the same
underlying value. All atomic reads/writes already go through
atomic.LoadInt64/atomic.StoreInt64, just without the address-of operator
now. Also drop the mutex in GetLevel and SetLevel since the atomics are
sufficient for thread safety on their own.

Fixes charmbracelet#184.
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.

Wrapped loggers don't inherit level changes

1 participant