I have run into a problem I have beat my head against the wall. Basically, I’m using this logging setup to log to a file, and it works great! However, I want to use this inside a method I built.. it won’t let me! It says it’s not a defined variable. I’m guessing this is a problem with variable scoping. How can I fix this?
This is my logging setup:
class MultiDelegator
def initialize(*targets)
@targets = targets
end
def self.delegate(*methods)
methods.each do |m|
define_method(m) do |*args|
@targets.map { |t| t.send(m, *args) }
end
end
self
end
class <<self
alias to new
end
end
log_file = File.open("/opt/sysnovo/log/server.log", "a")
log = Logger.new MultiDelegator.delegate(:write, :close).to(STDOUT, log_file
This is my method (deletes files):
def cleanup
log.info "Running cleanup"
dirs = [ "/opt/sysnovo/tmp", "/opt/sysnovo/data", "/opt/sysnovo/merge" ]
dirs.each do |dir|
# Our file count.
file_count = Dir.glob(File.join("#{dir}", '**', '*')).select { |file| File.file?(file) }.count
# Log and delete!
log.info "Removing #{file_count} files in #{dir}"
FileUtils.rm_rf("#{dir}/.", secure: true)
end
end
So basically, the log.info INSIDE the method fails with this:
./sysnovo_server.rb:58:in `<main>': undefined local variable or method `log' for main:Object (NameError)
So my QUESTION is this: how can I set up this to work right? Or get the log.info to work inside my method. Or .. am I doing this wrong? I’m new to Ruby so be gentle.
If you want to use the log variable inside your method then you should define it as global variable like this
But I would recommend that you create a Singleton class which handles the logging and use it to log.