如何登录没有环境的Rails应用程序的Ruby worker脚本?

时间:2022-06-01 19:06:34

I'm using rufus-scheduler for handling cron jobs for a Rails 3.2.x app. The root worker.rb is being fired off by foreman (actually upstart on this particular server) and therefore when it starts off it does not have the Rails context in which to operate. Obviously when I attempt to call logger or Rails.logger it will fail each time.

我正在使用rufus-scheduler来处理Rails 3.2.x应用程序的cron作业。 root worker.rb正在被foreman(在这个特定服务器上实际上是暴发户)解雇,因此当它开始时它没有Rails上下文来操作。显然,当我尝试调用logger或Rails.logger时,它每次都会失败。

I'm using log4r as a replacement for the default Rails Logger, which is quite nice, but I am wondering what the proper solution for this problem would be:

我使用log4r作为默认Rails Logger的替代品,这非常好,但我想知道这个问题的正确解决方案是什么:

1) Do I need to give the script the Rails context at startup (it is simply running rake tasks right now so it ends up getting the Rails environment when the worker script hands off to the rake task and I fear giving the script the Rails env before running the timed task would be overkill since it takes so long to fire up the env)? or

1)我是否需要在启动时为脚本提供Rails上下文(它现在只是运行rake任务,因此当工作脚本切换到rake任务时它最终会获得Rails环境,我担心给脚本提供Rails环境在运行定时任务之前会有点矫枉过正,因为启动env需要很长时间)?要么

2) Should I just set up log4r as one would do in a non-Rails Ruby script that simply reads in the same log4r.yml config that the Rails app is using and therefore participate in the same log structure?

2)我应该像在非Rails Ruby脚本中那样设置log4r,它只是读取Rails应用程序正在使用的相同log4r.yml配置,因此参与相同的日志结构?

3) Or some other option I'm not thinking of?

3)或者其他一些我没想到的选择?

Additionally, I would appreciate either an example or the steps that I should consider with the recommended implementation.

另外,我要感谢一个示例或我应该考虑推荐实现的步骤。

For reference, I followed "How to configure Log4r with Rails 3.0.x?" and I think this could be helpful when integrated with the above: "Properly using Log4r in Ruby Application?"

作为参考,我遵循“如何使用Rails 3.0.x配置Log4r?”我认为在与上述内容集成时可能会有所帮助:“在Ruby应用程序中正确使用Log4r?”

1 个解决方案

#1


1  

I think this might be what you're looking for..

我想这可能就是你要找的......

Use this within the worker itself, and create a custom named log file

在worker本身中使用它,并创建一个自定义命名日志文件

require 'log4r'

logger = Log4r::Logger.new('test')
logger.outputters << Log4r::Outputter.stdout
logger.outputters << Log4r::FileOutputter.new('logtest', :filename =>  'logtest.log')
logger.info('started script')

## You're actual worker methods go here

logger.info('finishing')

#1


1  

I think this might be what you're looking for..

我想这可能就是你要找的......

Use this within the worker itself, and create a custom named log file

在worker本身中使用它,并创建一个自定义命名日志文件

require 'log4r'

logger = Log4r::Logger.new('test')
logger.outputters << Log4r::Outputter.stdout
logger.outputters << Log4r::FileOutputter.new('logtest', :filename =>  'logtest.log')
logger.info('started script')

## You're actual worker methods go here

logger.info('finishing')