问题
Once the script is daemonized then the logger can't write to the file anymore. So how and when should I initialise the log?
require 'rubygems'
require 'daemons'
require 'logging'
def create_new_logger
logger = Logging.logger['trend-analyzer']
logger.add_appenders(
Logging.appenders.rolling_file('./logs/trend-analyzer.log'),
Logging.appenders.stdout
)
logger.level = :debug
return logger
end
logger = create_new_logger
#this log message gets written to the log file
logger.debug Time.new
Daemons.run_proc('ForestPress', :log_dir => '.logs', :backtrace => true) do
running_as_daemon = true
#this log message does NOT get written to the log file
logger.debug Time.new
loop do
#this log message does NOT get written to the log file
logger.info Time.new
sleep 5
end
end
EDIT
I notice the current path changes from where I executed the script to /
. Could this be why I can't log messages?
EDIT 2
I now save the original path before becoming a daemon and then use Dir.chdir
to set the path to the original path. I can then open the file directly and write to it. However the logging gem can't write to it still.
回答1:
Here is how it started working
require 'rubygems'
require 'daemons'
require 'logging'
def create_new_logger
logger = Logging.logger['trend-analyzer']
logger.add_appenders(
Logging.appenders.rolling_file('./logs/trend-analyzer.log'),
Logging.appenders.stdout
)
logger.level = :debug
return logger
end
current_dir = Dir.pwd
Daemons.run_proc('ForestPress', :log_dir => '.logs', :backtrace => true) do
Dir.chdir(current_dir)
logger = create_new_logger
loop do
puts Dir.pwd
logger.debug Time.new
sleep 5
end
end
来源:https://stackoverflow.com/questions/10749404/why-does-this-ruby-code-fail-to-write-to-the-log-file