lib/semantic_logger/logger.rb in semantic_logger-4.3.1 vs lib/semantic_logger/logger.rb in semantic_logger-4.4.0
- old
+ new
@@ -3,10 +3,29 @@
# Logger stores the class name to be used for all log messages so that every
# log message written by this instance will include the class name
class Logger < Base
include SemanticLogger::Concerns::Compatibility
+ def self.subscribe(object = nil, &block)
+ subscriber = block || object
+
+ unless subscriber.is_a?(Proc) || subscriber.respond_to?(:call)
+ raise('When supplying an on_log subscriber, it must support the #call method')
+ end
+
+ subscribers = (@subscribers ||= Concurrent::Array.new)
+ subscribers << subscriber unless subscribers.include?(subscriber)
+ end
+
+ class << self
+ attr_reader :subscribers
+ end
+
+ def self.processor
+ @processor
+ end
+
# Returns a Logger instance
#
# Return the logger for a specific class, supports class specific log levels
# logger = SemanticLogger::Logger.new(self)
# OR
@@ -30,12 +49,35 @@
super(klass, level, filter)
end
# Place log request on the queue for the Appender thread to write to each
# appender in the order that they were registered
+ #
+ # Subscribers are called inline before handing off to the queue so that
+ # they can capture additional context information as needed.
def log(log, message = nil, progname = nil, &block)
# Compatibility with ::Logger
return add(log, message, progname, &block) unless log.is_a?(SemanticLogger::Log)
- Processor << log
+
+ Logger.call_subscribers(log)
+
+ Logger.processor.log(log)
+ end
+
+ private
+
+ @processor = Processor.new
+ @subscribers = nil
+
+ def self.call_subscribers(log)
+ return unless @subscribers
+
+ @subscribers.each do |subscriber|
+ begin
+ subscriber.call(log)
+ rescue Exception => exc
+ self.class.processor.logger.error('Exception calling :on_log subscriber', exc)
+ end
+ end
end
end
end