为什么此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

修改

我注意到当前路径从执行脚本的位置改变为/。这可能是我为什么不能记录消息吗?


编辑2

我现在在成为守护进程之前保存原始路径,然后使用 Dir.chdir 将路径设置为原始路径。然后我可以直接打开文件并写入它。然而,日志gem仍然不能写入它。

3
额外 编辑
意见: 1

1 答案

这是它如何开始工作

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
0
额外