如何将脚本输出记录到STDOUT和文件

时间:2016-11-01 00:01:02

标签: ruby mixlib-shellout

我有以下Ruby块:

ruby_block "Validate" do
  block do
    require "mixlib/shellout"
    begin
      cmd = Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)
      cmd.live_stream = STDOUT
      cmd.run_command
      cmd.error!
    rescue Exception => e
      puts "Action failed..."
      return 168
    end
  end
  action :create
  notifies :create, "ruby_block[Validated]", :immediately
  not_if { node[:state][:validated] == true }
end

我想将脚本的结果记录到STDOUT和名为" /tmp/xml_diff_results.txt"的文件中。

我做的第一件事就是改变:

cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)

为:

cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py > /tmp/xml_diff_results.txt", :timeout => 3600)
然而,这并没有达到我的预期。

然后我注意到cmd.live_stream变量。有没有办法可以利用它做这样的事情?:

cmd.live_stream = (STDOUT > /tmp/xml_diff_results.txt)

SOLUTION:

我的问题的解决方案很简单,并且受到@tensibai的启发。

log_file = File.open('/tmp/chef-run.log', File::WRONLY | File::APPEND)
LOG = Logger.new(log_file)

def shell(command)
  LOG.info "Execute: #{command}"
  cmd = Mixlib::ShellOut.new(command, :timeout => 1800)
  cmd.run_command
  LOG.info "Returned: #{cmd.stdout}"
  cmd.error!
  cmd
end

2 个答案:

答案 0 :(得分:4)

这不是Ruby甚至是Chef的问题。它更像是一个Bash问题

运行命令并将其输出重定向到stdout和文件的一种方法是使用 tee

echo 'Hello World!' | tee output.log

所以,你的例子可能就像这样

cmd=Mixlib::ShellOut.new("/usr/local/bin/someScript.py | tee /tmp/xml_diff_results.txt", :timeout => 3600)

答案 1 :(得分:2)

Ruby中的另一个选项(只是内部部分)tee不可用(窗口):

  cmd = Mixlib::ShellOut.new("/usr/local/bin/someScript.py", :timeout => 3600)
  cmd.live_stream = STDOUT
  cmd.run_command
  # new part
  log=::Tempfile.new(["xml_diff_results",".txt"])
  errlog=::File.open(log.path.gsub(".txt",".err")
  log.write(cmd.stdout)
  errlog.write(cmd.stderr)
  log.close
  errlog.close
  Chef::Log.info("Log results are in #{log.path}")
  # end of new part 
  cmd.error!

如果您在没有Chef::Log的情况下运行chef-client,并且确实希望在主厨日志中打印路径,请将warn级别更改为-l info

主要优点是它与平台无关,缺点是只有在命令结束执行后才会写入日志文件。

相关问题