module Ki::HashLog

Generate hash object based log entries. @see log

Constants

HashLogMutex
HashLogThreadCurrentKey

Public Instance Methods

hash_log_current() click to toggle source
# File lib/util/hash_log.rb, line 87
def hash_log_current
  HashLogMutex.synchronize do
    (Thread.current[HashLogThreadCurrentKey] ||= []).last
  end
end
log(*args, &block) click to toggle source

Create a hash log entry or return current hash log entry

  • Supports hierarchic logs, where log entry can contain any number of sub entries

  • Supports parallel execution, threads can log in to one log structure

  • Logs start and stop time of execution

Hierarchic logging works by keeping a stack of log entries in Thread local store

@see set_hash_log_root_for_thread @see hash_log_current

# File lib/util/hash_log.rb, line 33
def log(*args, &block)
  current_log_entry = hash_log_current
  # return
  if args.empty? && block.nil?
    current_log_entry
  else
    new_entry = {"start" => Time.now}
    if args.first.kind_of?(String)
      new_entry["name"] = args.delete_at(0)
    end
    if args.first.kind_of?(Hash)
      new_entry.merge!(args.first)
    end
    log_list = nil
    if current_log_entry
      # there is current log entry, create a new sub log entry
      HashLogMutex.synchronize do
        log_list = current_log_entry["logs"] ||= []
      end
    else
      # append new_entry to end of log list
      log_list = Thread.current[HashLogThreadCurrentKey]
    end
    HashLogMutex.synchronize do
      log_list << new_entry
    end
    if block
      HashLogMutex.synchronize do
        Thread.current[HashLogThreadCurrentKey] << new_entry
      end
      begin
        block.call new_entry
      rescue Exception => e
        new_entry["exception"] = e.message
        new_entry["backtrace"] = e.backtrace.join("\n")
        raise
      ensure
        HashLogMutex.synchronize do
          Thread.current[HashLogThreadCurrentKey].delete(new_entry)
        end
        new_entry["end"] = Time.now
      end
    else
      new_entry
    end
  end
end
set_hash_log_root_for_thread(root) click to toggle source
# File lib/util/hash_log.rb, line 81
def set_hash_log_root_for_thread(root)
  HashLogMutex.synchronize do
    (Thread.current[HashLogThreadCurrentKey] ||= []) << root
  end
end