Navigation Menu

Skip to content

Output redirection aka logging your cron jobs

Dusan Orlovic edited this page Nov 19, 2020 · 10 revisions
In your schedule.rb file you can specify the redirection options for your commands at a global or command level by setting the 'output' variable. This example is global level:
  # adds ">> /path/to/file.log 2>&1" to all commands
  set :output, '/path/to/file.log'

and you should put this global level set :output above your job definition, otherwise it wouldn't work
Example:

# This works
set :output, {:error => '~/Desktop/z.error.log', :standard => '~/Desktop/z.standard.log'}

every 1.minute do
  command "python ~/Desktop/whe/config/z.py"
end
every 1.minute do
  command "python ~/Desktop/whe/config/z.py"
end

# This won't work
set :output, {:error => '~/Desktop/z.error.log', :standard => '~/Desktop/z.standard.log'}

Rails.root and RAILS_ROOT will be unavailable, however Whenever.path (or just path) will deliver the Rails root path in most cases. Alternatively, if you want to access environment or application config values, simply add

# makes Rails.root as well as other environment specific Rails.application.config values available
require File.expand_path(File.dirname(__FILE__) + "/environment")

Or you can STDOUT and STDERR separately,

  # adds ">> cron.log 2> error.log" to all commands
  set :output, {:error => 'error.log', :standard => 'cron.log'}

  # adds ">> cron.log" to all commands
  set :output, {:standard => 'cron.log'}

  # adds "2> error.log" to all commands
  set :output, {:error => 'error.log'}

Additionally you can set these values at the command level,

  every 3.hours do
    runner "MyModel.some_process", :output => 'cron.log'     
    rake "my:rake:task", :output => {:error => 'error.log', :standard => 'cron.log'}
    command "/usr/bin/cmd"
  end  

If you need to pipe output into a command, e.g. syslog (logger), use a lambda:

set :output, lambda { "2>&1 | logger -t whenever_cron" }

In all cases you can if you explicitly set the value of any output to 'nil' it will add a redirect to /dev/null

  # adds ">> /dev/null 2>&1" to all commands
  set :output, nil
  set :output, {:error => nil, :standard => nil}

  # adds ">> /dev/null" to all commands
  set :output, {:standard => nil}

  # adds "2> /dev/null" to all commands
  set :output, {:error => nil}

In Rails, to get log file into the logs directory you can use

  set :output, "#{path}/log/cron.log"