lib/semantic_logger/logger.rb in semantic_logger-2.6.1 vs lib/semantic_logger/logger.rb in semantic_logger-2.7.0

- old
+ new

@@ -103,15 +103,30 @@ def self.cache_count warn "[DEPRECATION] 'SemanticLogger::Logger.cache_count' is deprecated. Please use 'SemanticLogger::Logger.queue_size' instead." queue_size end + # Supply a block to be called whenever a metric is seen during benchmark logging + # + # Parameters + # block + # The block to be called + # + # Example: + # SemanticLogger.on_metric do |log_struct| + # puts "#{log_struct.metric} was received. Log Struct: #{log_struct.inspect}" + # end + def self.on_metric(&block) + (@@metric_subscribers ||= ThreadSafe::Array.new) << block + end + ############################################################################ protected - @@appender_thread = nil - @@queue = Queue.new + @@appender_thread = nil + @@queue = Queue.new + @@metric_subscribers = nil # Queue to hold messages that need to be logged to the various appenders def self.queue @@queue end @@ -165,10 +180,11 @@ appender.log(message) rescue Exception => exc logger.error "Appender thread: Failed to log to appender: #{appender.inspect}", exc end end + call_metric_subscribers(message) if message.metric count += 1 # Check every few log messages whether this appender thread is falling behind if count > lag_check_interval if (diff = Time.now - message.time) > lag_threshold_s logger.warn "Appender thread has fallen behind by #{diff} seconds with #{queue_size} messages queued up. Consider reducing the log level or changing the appenders" @@ -178,19 +194,19 @@ else case message[:command] when :flush SemanticLogger.appenders.each do |appender| begin - logger.info "Appender thread: Flushing appender: #{appender.name}" + logger.debug "Appender thread: Flushing appender: #{appender.name}" appender.flush rescue Exception => exc logger.error "Appender thread: Failed to flush appender: #{appender.inspect}", exc end end message[:reply_queue] << true if message[:reply_queue] - logger.info "Appender thread: All appenders flushed" + logger.debug "Appender thread: All appenders flushed" else logger.warn "Appender thread: Ignoring unknown command: #{message[:command]}" end end end @@ -207,9 +223,23 @@ # This block may be called after the file handles have been released by Ruby begin logger.debug "Appender thread has stopped" rescue Exception nil + end + end + end + + # Call Metric subscribers + def self.call_metric_subscribers(log_struct) + # If no subscribers registered, then return immediately + return unless @@metric_subscribers + + @@metric_subscribers.each do |subscriber| + begin + subscriber.call(log_struct) + rescue Exception => exc + logger.error "Exception calling subscriber", exc end end end end