为什么此Ruby代码无法写入日志文件? [英] Why does this Ruby code fail to write to the log file?

查看:89
本文介绍了为什么此Ruby代码无法写入日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


编辑

我注意到当前路径从执行脚本的位置更改为/.这可能是为什么我无法记录消息的原因吗?

I notice the current path changes from where I executed the script to /. Could this be why I can't log messages?

编辑2

我现在在成为守护程序之前保存了原始路径,然后使用Dir.chdir将路径设置为原始路径.然后,我可以直接打开文件并写入文件.但是,记录中的gem仍无法写入.

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.

推荐答案

这是它开始工作的方式

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

这篇关于为什么此Ruby代码无法写入日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆