1
0
Fork 0
mirror of https://github.com/mperham/sidekiq.git synced 2022-11-09 13:52:34 -05:00

Fix logger with from deleting existing context (#4770)

If using `with` to add logging context, any context that has the same
keys as existing context will disappear after the with block completes,
instead of reverting back to the original context.

This fixes that by restoring the original context directly instead of
just deleting the keys from the `with` context.
This commit is contained in:
Matt Robinson 2020-12-23 12:44:35 -08:00 committed by GitHub
parent 66a8155248
commit d4fca4683c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 1 deletions

View file

@ -6,10 +6,11 @@ require "time"
module Sidekiq module Sidekiq
module Context module Context
def self.with(hash) def self.with(hash)
orig_context = current.dup
current.merge!(hash) current.merge!(hash)
yield yield
ensure ensure
hash.each_key { |key| current.delete(key) } Thread.current[:sidekiq_context] = orig_context
end end
def self.current def self.current

View file

@ -49,6 +49,18 @@ class TestLogger < Minitest::Test
assert_equal({}, subject.current) assert_equal({}, subject.current)
end end
def test_with_overlapping_context
subject = Sidekiq::Context
subject.current.merge!({ foo: 'bar' })
assert_equal({ foo: 'bar' }, subject.current)
subject.with(foo: 'bingo') do
assert_equal({ foo: 'bingo' }, subject.current)
end
assert_equal({ foo: 'bar' }, subject.current)
end
def test_nested_contexts def test_nested_contexts
subject = Sidekiq::Context subject = Sidekiq::Context
assert_equal({}, subject.current) assert_equal({}, subject.current)