@@ -24,7 +24,8 @@ class Scope
2424 :span ,
2525 :session ,
2626 :attachments ,
27- :propagation_context
27+ :propagation_context ,
28+ :attributes
2829 ]
2930
3031 attr_reader ( *ATTRIBUTES )
@@ -84,7 +85,13 @@ def apply_to_event(event, hint = nil)
8485 # @param telemetry [MetricEvent, LogEvent] the telemetry event to apply scope context to
8586 # @return [MetricEvent, LogEvent] the telemetry event with scope context applied
8687 def apply_to_telemetry ( telemetry )
87- # TODO-neel when new scope set_attribute api is added: add them here
88+ attributes . each do |key , value |
89+ # Compare as strings since String and Symbol keys serialize to the same wire key.
90+ next if telemetry . attributes . keys . any? { |existing | existing . to_s == key . to_s }
91+
92+ telemetry . attributes [ key ] = value
93+ end
94+
8895 trace_context = get_trace_context
8996 telemetry . trace_id = trace_context [ :trace_id ]
9097 telemetry . span_id = trace_context [ :span_id ]
@@ -136,6 +143,7 @@ def dup
136143 copy . propagation_context = propagation_context . deep_dup
137144 copy . attachments = attachments . dup
138145 copy . event_processors = event_processors . dup
146+ copy . attributes = attributes . deep_dup
139147 copy
140148 end
141149
@@ -154,6 +162,7 @@ def update_from_scope(scope)
154162 self . span = scope . span
155163 self . propagation_context = scope . propagation_context
156164 self . attachments = scope . attachments
165+ self . attributes = scope . attributes
157166 end
158167
159168 # Updates the scope's data from the given options.
@@ -256,6 +265,31 @@ def set_context(key, value)
256265 set_contexts ( key => value )
257266 end
258267
268+ # Updates the scope's attributes by merging with the old value.
269+ # @param attributes_hash [Hash]
270+ # @return [Hash]
271+ def set_attributes ( attributes_hash )
272+ check_argument_type! ( attributes_hash , Hash )
273+ @attributes . merge! ( attributes_hash )
274+ end
275+
276+ # Sets a single attribute on the scope.
277+ # @param key [String, Symbol]
278+ # @param value [Object]
279+ # @param unit [String, Symbol, nil] an optional measurement unit for the value
280+ # @return [Hash]
281+ def set_attribute ( key , value , unit : nil )
282+ value = { value : value , unit : unit } unless unit . nil?
283+ set_attributes ( key => value )
284+ end
285+
286+ # Removes a single attribute from the scope. No-op if the attribute is not set.
287+ # @param key [String, Symbol]
288+ # @return [void]
289+ def remove_attribute ( key )
290+ @attributes . delete ( key )
291+ end
292+
259293 # Sets the scope's level attribute.
260294 # @param level [String, Symbol]
261295 # @return [void]
@@ -361,6 +395,7 @@ def set_default_value
361395 @span = nil
362396 @session = nil
363397 @attachments = [ ]
398+ @attributes = { }
364399 generate_propagation_context
365400 set_new_breadcrumb_buffer
366401 end
0 commit comments