Skip to content

Instantly share code, notes, and snippets.

@kares
Last active September 25, 2015 10:58
Show Gist options
  • Save kares/911210 to your computer and use it in GitHub Desktop.
Save kares/911210 to your computer and use it in GitHub Desktop.
a really threadsafe! (buffered) logger
require 'thread'
require 'active_support/buffered_logger'
# ActiveSupport::BufferedLogger is not completely thread-safe !
# well it is if you disable the silencer :
#
# ActiveSupport::BufferedLogger.silencer = false
#
# yet Rails might still re-invent the silencing logic and set the
# `logger.level = Logger::ERROR` by hand instead of delegating to
# `logger.silence` ... if you'd like to use `logger.silence { }`
# without permanently changing the level if 2 threads perform
# silencing at the same time you do need a thread-safe logger ...
class ThreadSafeLogger < ActiveSupport::BufferedLogger
def level
Thread.current[thread_hash_level_key] || @level
end
def level=(level)
if @level == level
Thread.current[thread_hash_level_key] = nil
else
Thread.current[thread_hash_level_key] = level
end
level
end
# now override where ActiveSupport::BufferedLogger uses @level :
def add(severity, message = nil, progname = nil, &block)
return if level > severity
message = (message || (block && block.call) || progname).to_s
message = "#{message}\n" unless message[-1] == ?\n
buffer << message
auto_flush
message
end
for severity in Severity.constants
class_eval <<-EOT, __FILE__, __LINE__ + 1
def #{severity.downcase}? # def debug?
#{severity} >= level # DEBUG >= level
end # end
EOT
end
private
def thread_hash_level_key
@thread_hash_level_key ||= :"ThreadSafeLogger##{object_id}@level"
end
end
@slawosz
Copy link

slawosz commented Apr 17, 2013

Should not

@thread_hash_level_key ||= :"ThreadSafeLogger##{object_id}@level"

be

@thread_hash_level_key ||= :"ThreadSafeLogger##{object_id}#{@level}"

?

@slawosz
Copy link

slawosz commented Apr 18, 2013

Ok, my mistake, it wont work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment