简体   繁体   English

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

[英]Why does this Ruby code fail to write to the log file?

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 编辑2

I now save the original path before becoming a daemon and then use Dir.chdir to set the path to the original path. 我现在在成为守护进程之前保存原始路径,然后使用Dir.chdir设置原始路径的路径。 I can then open the file directly and write to it. 然后我可以直接打开文件并写入它。 However the logging gem can't write to it still. 但是,日志记录宝石仍然无法写入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM