diff --git a/lib/foreman/cli.rb b/lib/foreman/cli.rb index 67d697ab..2c43ac88 100644 --- a/lib/foreman/cli.rb +++ b/lib/foreman/cli.rb @@ -25,6 +25,8 @@ class Foreman::CLI < Foreman::Thor method_option :port, :type => :numeric, :aliases => "-p" method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5." method_option :timestamp, :type => :boolean, :default => true, :desc => "Include timestamp in output" + method_option :output_format, :type => :string, :default => "text", :desc => "Specify the output format you wish, text or json. Default: text" + method_option :json_message_key, :type => :string, :default => "message", :desc => "The key used to put a text based output from your process. Default: message" class << self # Hackery. Take the run method away from Thor so that we can redefine it. diff --git a/lib/foreman/engine/cli.rb b/lib/foreman/engine/cli.rb index 7ea71375..761099a7 100644 --- a/lib/foreman/engine/cli.rb +++ b/lib/foreman/engine/cli.rb @@ -55,14 +55,34 @@ def startup def output(name, data) data.to_s.lines.map(&:chomp).each do |message| - output = "" - output += $stdout.color(@colors[name.split(".").first].to_sym) - output += "#{Time.now.strftime("%H:%M:%S")} " if options[:timestamp] - output += "#{pad_process_name(name)} | " - output += $stdout.color(:reset) - output += message - $stdout.puts output - $stdout.flush + case options[:output_format] + when "text" + output = "" + output += $stdout.color(@colors[name.split(".").first].to_sym) + output += "#{Time.now.strftime("%H:%M:%S")} " if options[:timestamp] + output += "#{pad_process_name(name)} | " + output += $stdout.color(:reset) + output += message + $stdout.puts output + $stdout.flush + when "json" + require 'json' + json_data = {foreman_process: name} + begin + result = JSON.parse(message) + if result.is_a?(Hash) + json_data.merge!(result) + else + json_data[options[:json_message_key]] = message + end + rescue JSON::ParserError, TypeError + json_data[options[:json_message_key]] = message + end + $stdout.puts json_data.to_json + $stdout.flush + else + raise "Invalid output format: #{options[:output_format]}" + end end rescue Errno::EPIPE terminate_gracefully