Last active
September 25, 2015 10:58
-
-
Save kares/911210 to your computer and use it in GitHub Desktop.
a really threadsafe! (buffered) logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should not
be
?