Permalink
Browse files

Merge pull request #7 from fabiokung/master

first attempt at avoiding race conditions
  • Loading branch information...
2 parents a48f818 + 89e8f4b commit bdd22b7eceb34559a115fb1f93ea408491426504 @asenchi asenchi committed Apr 26, 2012
Showing with 27 additions and 22 deletions.
  1. +26 −22 lib/scrolls.rb
  2. +1 −0 scrolls.gemspec
View
48 lib/scrolls.rb
@@ -1,4 +1,5 @@
require "thread"
+require "atomic"
require "scrolls/version"
@@ -13,8 +14,12 @@ def log_exception(data, e)
Log.log_exception(data, e)
end
+ def global_context(data)
+ Log.global_context = data
+ end
+
def context(data, &blk)
- Log.set_context(data, &blk)
+ Log.with_context(data, &blk)
end
module Log
@@ -34,14 +39,23 @@ module Log
"debug" => 7
}
- attr_accessor :stream, :context
+ attr_accessor :stream
+
+ def context
+ Thread.current[:scrolls_context] ||= {}
+ end
+
+ def context=(hash)
+ Thread.current[:scrolls_context] = hash
+ end
def start(out = nil)
# This allows log_exceptions below to pick up the defined output,
# otherwise stream out to STDERR
@defined = out.nil? ? false : true
sync_stream(out)
+ @global_context = Atomic.new({})
end
def sync_stream(out = nil)
@@ -87,11 +101,8 @@ def unparse(data)
end
def log(data, &blk)
- if @context
- logdata = @context.merge(data)
- else
- logdata = data
- end
+ merged_context = @global_context.value.merge(context)
+ logdata = merged_context.merge(data)
unless blk
write(logdata)
@@ -145,23 +156,16 @@ def log_level_ok?(level)
end
end
- def set_context(prefix, &blk)
- # Initialize an empty context if the variable doesn't exist
- @context = {} unless @context
- @stash = [] unless @stash
- @stash << @context
- # Why isn't this merging
- @context = @context.merge(prefix)
-
- if blk
- yield
- @context = @stash.pop
- end
+ def with_context(prefix)
+ return unless block_given?
+ old_context = context
+ self.context = old_context.merge(prefix)
+ yield if block_given?
+ self.context = old_context
end
- def clear_context
- @stash = []
- @context = {}
+ def global_context=(data)
+ @global_context.update { |_| data }
end
end
View
1 scrolls.gemspec
@@ -13,4 +13,5 @@ Gem::Specification.new do |gem|
gem.name = "scrolls"
gem.require_paths = ["lib"]
gem.version = Scrolls::VERSION
+ gem.add_dependency("atomic", "~> 1.0.0")
end

0 comments on commit bdd22b7

Please sign in to comment.