module Eco module API module Common module Session class Logger class Cache LEVELS = %w[UNKNOWN FATAL ERROR WARN INFO DEBUG].freeze def initialize reset end def level(level) cache[to_level(level)] ||= [] end def add(level, datetime, message, formatted) Logger::Log.new(level, datetime, message, formatted).tap do |log| self.level(level).push(log) end end def cache @cache ||= {} end def reset(level: nil, start_time: nil, end_time: nil) where(start_time, end_time) do |cond| to_levels(level).map do |lev| self.level(lev).reject(&cond) end end self end def logs(level: nil, start_time: nil, end_time: nil) where(start_time, end_time) do |cond| to_levels(level).map do |lev| self.level(lev).select(&cond) end.flatten end.sort end private def where(start_time, end_time) tstart = to_datetime(start_time) tend = to_datetime(end_time) condition = proc do |log| next true unless tstart || tend log.after?(tstart) && log.before?(tend) end yield(condition) end def to_datetime(value) return nil unless value Time.parse(value) end def to_levels(value) levels = [value].flatten.map {|v| to_level(v)}.compact return levels unless levels.empty? LEVELS end def to_level(value) nil_or_upcase(value).tap do |out| valid_level!(out) end end def valid_level!(str) return true unless str return true if LEVELS.any? {|lev| str == lev} msg = "Unknown level #{str}. Should be one of #{LEVELS}" raise ArgumentError, msg end def nil_or_upcase(value) value = value.to_s.upcase if value return yield(value) if block_given? value end end end end end end end