lib/stash/sword/log_utils.rb in stash-sword-0.1.3 vs lib/stash/sword/log_utils.rb in stash-sword-0.1.4
- old
+ new
@@ -5,25 +5,19 @@
def log
@log ||= default_logger
end
def log_error(e)
- if e.respond_to?(:response)
- log.error(response_to_log_msg(e.response))
- else
- log.error('Unable to log response')
- end
+ log.error(to_log_msg(e))
end
- def response_to_log_msg(response)
- [
- '-----------------------------------------------------',
- "code: #{response.code}",
- 'headers:', hash_to_log_msg(response.headers),
- "body:\n#{response.body}",
- '-----------------------------------------------------'
- ].join("\n")
+ def to_log_msg(e)
+ msg_lines = []
+ append_message(msg_lines, e)
+ append_response(msg_lines, e)
+ append_backtrace(msg_lines, e)
+ msg_lines.join("\n")
end
def log_hash(hash)
msg = hash_to_log_msg(hash)
log.debug(msg)
@@ -47,15 +41,44 @@
Logger::WARN
end
end
def default_logger
- logger = Logger.new($stdout, 10, 1024 * 1024)
+ LogUtils.create_default_logger($stdout, level)
+ end
+
+ def self.create_default_logger(io, level)
+ logger = Logger.new(io, 10, 1024 * 1024)
logger.level = level
logger.formatter = proc do |severity, datetime, progname, msg|
"#{datetime.to_time.utc} #{severity} -#{progname}- #{msg}\n"
end
logger
+ end
+
+ private
+
+ def append_message(msg_lines, e)
+ msg_lines << if e.respond_to?(:message) && e.message
+ "message: #{e.message}"
+ else
+ e.to_s
+ end
+ end
+
+ def append_response(msg_lines, e)
+ return unless e.respond_to?(:response) && e.response
+ response = e.response
+ msg_lines.unshift(*[
+ "code: #{response.code}",
+ 'headers:', hash_to_log_msg(response.headers),
+ "body:\n#{response.body}"
+ ])
+ end
+
+ def append_backtrace(msg_lines, e)
+ return unless e.respond_to?(:backtrace) && e.backtrace
+ msg_lines.unshift(*e.backtrace)
end
end
end
end