class EC2Ctl::Logger
Constants
- InvalidOutputFormat
- VALID_FORMATS
Public Class Methods
new( output_format: :json, null_output: false, pretty: false, verbose: false, std_io: STDOUT, err_io: STDERR )
click to toggle source
# File lib/ec2ctl/logger.rb, line 12 def initialize( output_format: :json, null_output: false, pretty: false, verbose: false, std_io: STDOUT, err_io: STDERR ) @output_format = output_format @null_output = null_output @std_logger = ::Logger.new std_io @err_logger = ::Logger.new err_io @std_logger.level = verbose ? ::Logger::DEBUG : ::Logger::INFO @err_logger.level = verbose ? ::Logger::DEBUG : ::Logger::INFO @std_logger.formatter = formatter(std_io, pretty) @err_logger.formatter = formatter(err_io, pretty) self end
Private Instance Methods
formatter(io, pretty)
click to toggle source
# File lib/ec2ctl/logger.rb, line 73 def formatter(io, pretty) -> (severity, time, progname, message) { return "" if @null_output data = { time: time, severity: severity, }.merge( if message.is_a? Hash message else {message: message} end ) case @output_format when /\Ajson\z/i require "json" json = JSON.send((pretty ? :pretty_generate : :generate), data) + "\n" if io.tty? require "coderay" CodeRay.scan(json, :json).terminal else json end when /\Ayaml\z/i require "yaml" # korehahidoi require "json" yaml = YAML.dump(JSON.load(JSON.generate(data))) if io.tty? require "coderay" CodeRay.scan(yaml, :yaml).terminal else yaml end when /\Atable|markdown|backlog\z/i require "terminal-table" require "json" title, content = data.find {|k, v| !%i(time severity).include?(k)} headings, rows = begin case content when Hash row = content.values.map do |value| case value when Hash, Array JSON.generate value else value.to_s end end [content.keys.map(&:to_s), [row]] when Array if content.first.is_a? Hash rows = content.map do |item| item.values.map do |value| case value when Hash, Array JSON.generate value else value.to_s end end end [content.first.keys, rows] else [["items"], [content]] end else fail end rescue [["data"], [[content.to_json]]] end table = Terminal::Table.new( title: (@output_format == :table ? title : nil), headings: headings, rows: rows, ).to_s output = case @output_format when /\Atable\z/i table + "\n" when /\Amarkdown\z/i lines = table.lines[1..-2] lines[1].gsub!("+", "|") lines.join when /\Abacklog\z/i lines = table.lines[1..-2] lines[0].sub!("\n", "h\n") lines[1] = nil lines.compact.join end output + "\n" else fail InvalidOutputFormat, "Valid output formats are #{VALID_FORMATS}" end } end
to_hash(object)
click to toggle source
# File lib/ec2ctl/logger.rb, line 50 def to_hash(object) case object when Struct Hash[ object.each_pair.to_a.map {|a| [a.first, to_hash(a.last)] } ] when Hash Hash[ object.to_a.map {|a| [a.first, to_hash(a.last)] } ] when Array, Aws::Resources::Collection object.map {|o| to_hash(o)} when Aws::Resources::Resource to_hash object.data else object end end