为什么这个Ruby代码无法写入日志文件?

时间:2012-05-25 06:17:45

标签: ruby-on-rails ruby logging daemon

一旦脚本被守护,那么记录器就不能再写入该文件了。那么我应该如何以及何时初始化日志?

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

修改

我注意到当前路径从我执行脚本的地方变为/。这可能是我无法记录消息的原因吗?


编辑2

我现在在成为守护进程之前保存原始路径,然后使用Dir.chdir设置原始路径的路径。然后我可以直接打开文件并写入它。但是,日志记录宝石仍然无法写入。

1 个答案:

答案 0 :(得分: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