@@ -38,6 +38,11 @@ def remove(*args)
38
38
def reset ( *args )
39
39
instance . reset ( *args )
40
40
end
41
+
42
+ # Convenience method for {CurrentContext#with}. See {CurrentContext#with} for more info.
43
+ def with ( *args , &block )
44
+ instance . with ( *args , &block )
45
+ end
41
46
end
42
47
43
48
# Adds contexts but does not remove them. See {#with} for automatic maintenance and {#remove}
@@ -68,6 +73,12 @@ def remove(*keys)
68
73
self
69
74
end
70
75
76
+ def replace ( hash )
77
+ @hash = hash
78
+ expire_cache!
79
+ self
80
+ end
81
+
71
82
# Resets the context to be blank. Use this carefully! This will remove *any* context,
72
83
# include context that is automatically included with Timber.
73
84
def reset
@@ -83,6 +94,35 @@ def snapshot
83
94
@snapshot ||= hash . clone
84
95
end
85
96
97
+ # Adds a context and then removes it when the block is finished executing.
98
+ #
99
+ # @note Because context is included with every log line, it is recommended that you limit this
100
+ # to only neccessary data.
101
+ #
102
+ # @example Adding a custom context
103
+ # Timber::CurrentContext.with({build: {version: "1.0.0"}}) do
104
+ # # ... anything logged here will include the context ...
105
+ # end
106
+ #
107
+ # @note Any custom context needs to have a single root key to be valid. i.e. instead of:
108
+ # Timber::CurrentContext.with(job_id: "123", job_name: "Refresh User Account")
109
+ #
110
+ # do
111
+ #
112
+ # Timber::CurrentContext.with(job: {job_id: "123", job_name: "Refresh User Account"})
113
+ #
114
+ # @example Adding multiple contexts
115
+ # Timber::CurrentContext.with(context1, context2) { ... }
116
+ def with ( *objects )
117
+ old_hash = hash . clone
118
+ begin
119
+ add ( *objects )
120
+ yield
121
+ ensure
122
+ replace ( old_hash )
123
+ end
124
+ end
125
+
86
126
private
87
127
# The internal hash that is maintained. Use {#with} and {#add} for hash maintenance.
88
128
def hash
0 commit comments