2012-05-25 70 views
3

腳本被守護進程後,記錄器不能再寫入文件。那麼應該如何以及何時應該初始化日誌?爲什麼Ruby代碼無法寫入日誌文件?

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 2

我現在已經成爲一個守護進程之前保存原始路徑,然後使用Dir.chdir的路徑設置爲原始路徑。然後我可以直接打開文件並寫入它。但是日誌gem仍然不能寫入它。

回答

0

這裏是如何開始工作

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