lib/timber/current_context.rb in timberio-1.0.0.beta1 vs lib/timber/current_context.rb in timberio-1.0.0
- old
+ new
@@ -1,58 +1,43 @@
-require "set"
+require "singleton"
module Timber
- # Holds the current context in the current thread's memory.
- # This context gets copied as each log line is written.
+ # Holds the current context in a thread safe memory storage. This context is
+ # appended to every log line. Think of context as join data between your log lines,
+ # allowing you to relate them and filter them appropriately.
class CurrentContext
+ include Singleton
+
THREAD_NAMESPACE = :_timber_current_context.freeze
- STACK_KEYNAME = :stack.freeze
- PRECISION = 8.freeze
- include Patterns::DelegatedSingleton
+ class << self
+ # Convenience method for {#with}.
+ #
+ # @example Adding a context
+ # custom_context = Timber::Contexts::Custom.new(type: :keyspace, data: %{my: "data"})
+ # Timber::CurrentContext.with(custom_context) do
+ # # ... anything logged here will have the context ...
+ # end
+ def with(*args, &block)
+ instance.with(*args, &block)
+ end
+ end
# Adds a context to the current stack.
- def add(*contexts, &_block)
- contexts = contexts.compact
- contexts.each do |context|
- stack << context
- end
- block_given? ? yield : self
+ def with(data)
+ key = data.keyspace
+ hash[key] = data
+ yield
ensure
- remove(*contexts) if block_given?
+ hash.delete(key)
end
- # Get a specific context type off the stack
- def get(type)
- stack.find { |context| context.is_a?(type) }
- end
-
- # Removes the contexts from the current stack.
- def remove(*contexts)
- # Ensure we clear the cacke when the stack changes
- contexts.each do |context|
- CurrentLineIndexes.context_removed(context)
- stack.delete(context)
- end
- self
- end
-
- # Used to efficiently clone the context
def snapshot
- # Cloning the array is efficient and will point to the same objects.
- Timber::ContextSnapshot.new
+ hash.clone
end
- def valid_stack
- stack.select(&:valid?)
- end
-
private
- def stack
- storage[STACK_KEYNAME] ||= []
- end
-
- def storage
+ def hash
Thread.current[THREAD_NAMESPACE] ||= {}
end
end
-end
+end
\ No newline at end of file