require 'logger' require 'rainbow' module Onering class Logger def self.setup(options={}) outputfn = options[:destination] if options[:destination] == /STDOUT/i options[:destination] = STDOUT elsif options[:destination] == /STDERR/i or options[:destination].nil? options[:destination] = STDERR elsif File.writable?(options[:destination]) options[:destination] = File.open(options[:destination], 'a') else options[:destination] = STDERR end @_logger = ::Logger.new(options[:destination]) @_logger.formatter = (options[:formatter] || proc{|severity, datetime, source, msg| case severity.downcase.to_sym when :fatal then sevtag = '!!' when :error then sevtag = 'EE' when :warn then sevtag = 'WW' when :info then sevtag = 'II' when :debug then sevtag = 'DD' else sevtag = '??' end logline = ["#{sevtag} ", (source.nil? ? nil : "[#{source}]"), msg].compact.join(' ') if options[:destination] === STDOUT or options[:destination] === STDERR case severity.downcase.to_sym when :fatal, :error logline = logline.foreground(:red) when :warn logline = logline.foreground(:yellow) when :info logline = logline.foreground(:green) when :debug logline = logline.foreground(:blue) end end options[:destination].puts(logline) }) self.level = options[:threshold] self.debug("Logger is initialized. Output is #{outputfn}, threshold: #{options[:threshold]} or worse", "Onering::Logger") end def self.level=(severity) @_logger.sev_threshold = _get_level(severity) @_logger.sev_threshold end def self.log(severity, message, source=nil) if defined?(@_logger) @_logger.add(_get_level(severity), message, source) return true end return false end def self.fatal(message, source=nil, raise_error=false) self.log(:fatal, message, source) raise Onering::Client::FatalError.new(message) if raise_error === true end def self.fatal!(message, source=nil) self.fatal(message, source, true) end def self.error(message, source=nil) self.log(:error, message, source) end def self.warn(message, source=nil) self.log(:warn, message, source) end def self.info(message, source=nil) self.log(:info, message, source) end def self.debug(message, source=nil) self.log(:debug, message, source) end def self._get_level(severity) case severity.to_sym when :fatal return ::Logger::FATAL when :error return ::Logger::ERROR when :warn return ::Logger::WARN when :info return ::Logger::INFO else return ::Logger::DEBUG end end end end