Class: Betterlog::GlobalMetadata

Inherits:
Object
  • Object
show all
Includes:
Tins::SexySingleton
Defined in:
lib/betterlog/global_metadata.rb

Overview

Thread-local storage for global metadata used to enrich log events.

This class provides a thread-safe mechanism to store and manage metadata that should be included with log events. It ensures that metadata is scoped to the current thread and can be easily added, removed, or temporarily applied within a block context.

See Also:

Instance Method Summary collapse

Instance Method Details

#add(data) ⇒ Betterlog::GlobalMetadata

Adds metadata to the current thread-local storage.

This method takes a hash of data and merges it with the existing metadata in the current thread’s storage. The provided data is symbolized and then combined with the current metadata using a union operation, ensuring that new keys overwrite existing ones with the same name.

Parameters:

  • data (Hash)

    A hash containing the metadata to be added

Returns:



31
32
33
34
35
# File 'lib/betterlog/global_metadata.rb', line 31

def add(data)
  data = data.symbolize_keys_recursive
  self.current = data | current
  self
end

#remove(data) ⇒ void

This method returns an undefined value.

Removes metadata keys from the current thread-local storage.

This method takes a hash or array of keys and deletes the corresponding entries from the global metadata stored in the current thread. It ensures that only the specified keys are removed, leaving other metadata intact.

of key symbols

Parameters:

  • data (Hash, Array)

    A hash containing keys to remove or an array



46
47
48
49
# File 'lib/betterlog/global_metadata.rb', line 46

def remove(data)
  keys = data.ask_and_send_or_self(:keys).map(&:to_sym)
  keys.each { current.delete(_1) }
end

#with_meta(data = {}) {|data| ... } ⇒ void

This method returns an undefined value.

Temporarily adds metadata to the current thread-local storage for the duration of a block execution.

This method allows for the temporary addition of metadata to the global metadata store within the context of a block. The metadata is automatically removed after the block completes, ensuring that the metadata changes do not persist beyond the intended scope.

Parameters:

  • data (Hash) (defaults to: {})

    A hash containing the metadata key-value pairs to be added

Yields:

  • (data)

    Executes the provided block with the metadata in place



62
63
64
65
66
67
# File 'lib/betterlog/global_metadata.rb', line 62

def with_meta(data = {}, &block)
  add data
  block.call
ensure
  remove data
end