Rake: Logging Any Task Executing

Rake: logging any task executing

You can override Rake::Task#invoke method in application.rb:

#application.rb
module Rake
class Task
alias_method :origin_invoke, :invoke if method_defined?(:invoke)
def invoke(*args)
logger = Logger.new('rake_tasks_log.log')
logger.info "#{Time.now} -- #{name} -- #{args.inspect}"
origin_invoke(*args)
end
end
end

output for rake test:

2011-05-27 16:57:42 +0300 -- test -- []
2011-05-27 16:57:42 +0300 -- test:units -- []
2011-05-27 16:57:51 +0300 -- db:test:load -- []
2011-05-27 16:57:51 +0300 -- db:schema:load -- []
2011-05-27 16:58:19 +0300 -- test:functionals -- []
2011-05-27 16:58:49 +0300 -- test:integration -- []

Rails: Log rake task

The problem is the logger.close, look after boot you server for a message like this:

log writing failed. closed stream

try removing logger.close from your code and restarting your server.

Rails : How to log all exceptions thrown in rake tasks

You can achieve this task, by monkey-patching rake as shown below

module Rake
class Task
alias_method :invoke_without_loggable, :invoke

def invoke(*args)
begin
invoke_without_loggable(*args)
rescue StandardError => e
ErrorLogger.log(e)
raise e
end
end
end
end

Rake - save log from each task to separate file

Use String Interpolation to Create One Logfile Per Rake::Task

You can use a Rake::Task#name to get the name of the current task to interpolate into the name of your logfile. You can also use the task name as the progname for your log entry.

A Rakefile can also contain arbitrary Ruby code in addition to standard Rake methods. You can use this to create a custom logging method that allows you to create a log per Rake task, with your shell command's standard output captured using the Kernel#` method and passed along to the custom logging method as the log message.

A Worked Example

Rakefile

require 'logger'

def log task, msg
l = Logger.new "#{task}.log"
l.progname = task
l.info msg
end

task :foo do |task|
msg = `echo Hello, world.`
log task.name, msg
end

task :bar do |task|
msg = `echo Goodbye, cruel world.`
log task.name, msg
end

task :default => [:foo, :bar]

Sample Output

$ rake; tail +1 *log
==> bar.log <==
# Logfile created on 2016-03-02 17:31:49 -0500 by logger.rb/53141
I, [2016-03-02T17:31:49.678729 #80846] INFO -- bar: Goodbye, cruel world.

==> foo.log <==
# Logfile created on 2016-03-02 17:31:49 -0500 by logger.rb/53141
I, [2016-03-02T17:31:49.677165 #80846] INFO -- foo: Hello, world.

How to see rake task puts / logs inside rails server?

I put this on very top of my controller:

require 'rake'
Rails.application.load_tasks

And inside the action that calling the rake task, I replaced %x(bundle exec rake task_name) with Rake::Task["task_name"].invoke.

Thanks mudasobwa for the help!



Related Topics



Leave a reply



Submit