Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
move tagged logging to a module, stop proxying every method call
  • Loading branch information
tenderlove authored and prasath committed Feb 7, 2012
1 parent 899d866 commit c837366
Showing 1 changed file with 32 additions and 36 deletions.
68 changes: 32 additions & 36 deletions activesupport/lib/active_support/tagged_logging.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/object/blank'
require 'logger'
require 'active_support/logger'

module ActiveSupport
# Wraps any standard Logger class to provide tagging capabilities. Examples:
Expand All @@ -11,52 +12,47 @@ module ActiveSupport
#
# This is used by the default Rails.logger as configured by Railties to make it easy to stamp log lines
# with subdomains, request ids, and anything else to aid debugging of multi-user production applications.
class TaggedLogging
def initialize(logger)
@logger = logger
module TaggedLogging
class Formatter < ActiveSupport::Logger::SimpleFormatter # :nodoc:
# This method is invoked when a log event occurs
def call(severity, timestamp, progname, msg)
super(severity, timestamp, progname, "#{tags_text}#{msg}")
end

def clear!
current_tags.clear
end

def current_tags
Thread.current[:activesupport_tagged_logging_tags] ||= []
end

private
def tags_text
tags = current_tags
if tags.any?
tags.collect { |tag| "[#{tag}] " }.join
end
end
end

def self.new(logger)
logger.formatter = Formatter.new
logger.extend(self)
end

def tagged(*new_tags)
tags = current_tags
new_tags = Array(new_tags).flatten.reject(&:blank?)
tags = formatter.current_tags
new_tags = new_tags.flatten.reject(&:blank?)
tags.concat new_tags
yield
ensure
tags.pop(new_tags.size)
end

def add(severity, message = nil, progname = nil, &block)
@logger.add(severity, "#{tags_text}#{message}", progname, &block)
end

%w( fatal error warn info debug unknown ).each do |severity|
eval <<-EOM, nil, __FILE__, __LINE__ + 1
def #{severity}(progname = nil, &block) # def warn(progname = nil, &block)
add(Logger::#{severity.upcase}, progname, &block) # add(Logger::WARN, progname, &block)
end # end
EOM
end

def flush
current_tags.clear
@logger.flush if @logger.respond_to?(:flush)
end

def method_missing(method, *args)
@logger.send(method, *args)
end

protected

def tags_text
tags = current_tags
if tags.any?
tags.collect { |tag| "[#{tag}] " }.join
end
end

def current_tags
Thread.current[:activesupport_tagged_logging_tags] ||= []
formatter.clear!
super if defined?(super)
end
end
end

0 comments on commit c837366

Please sign in to comment.