在Ruby应用程序中正确使用Log4r [英] Properly using Log4r in Ruby Application

查看:87
本文介绍了在Ruby应用程序中正确使用Log4r的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实必须确实缺少一些明显的东西,但是我在Ruby应用程序中普遍使用Log4r时遇到了麻烦.我可以无问题地进行日志记录,但是在设置过程中,开销似乎有些笨拙.我基本上是将完整路径传递给文件名,以登录应用程序中的每个类.调用的ruby脚本从ARGV中的一个参数中提取日志文件,然后将其传递并设置在我在ruby中调用的每个类中.在每个类中,我都使用patternFormatter将类/文件名插入到log语句中.

I must really be missing something obvious, but I'm having trouble with general use of Log4r in my Ruby application. I am able to log without issue, but the overhead seems clunky the way I have it setup. I'm basically passing the full path to a filename to log in each class in my application. The ruby script that is called pulls the log file from one of the arguments in ARGV which is then passed around and set in each class that I call in ruby. In each class I use the patternFormatter to insert the class/file name into the log statement.

是否有更好的方法可以完成这项工作?感觉不管我怎么想,都需要将某些内容传递给我的ruby应用程序中的每个类.我可以将日志文件设置在yaml配置文件中,但是随后我还将配置文件传递给每个类.

Is there a better way to make this work? It feels like no matter what I think of will require something to be passed to each class in my ruby application. I could set the log file in a yaml configuration file instead, but then I would be passing around the configuration file to each class as well.

有什么建议吗?如果这样做没有意义,我可以尝试发布一些更具体的代码示例以进一步解释我的意思.

Any advice? If this doesn't make sense I could try and post some more specific code samples to further explain what I mean.

谢谢!

推荐答案

嗯,您为什么不在脚本开始时实例化Log4r::Logger类并传递实例的任何原因?您甚至不必传递它,您总是可以从Logger类中通过名称获取它:

Hmm, any reason why you don't instantiate Log4r::Logger class at the beginning of your script and pass the instance around? You don't even have to pass it around, you can always get it by name from Logger class:

run.rb:

require 'log4r'
require 'class_a'

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

class_a.rb:

class_a.rb:

class A
  def do_something
    logger = Log4r::Logger['test']
    logger.info('in do_something')
    puts 'hi!'
  end
end

,当您运行run.rb时,您会得到:

and when you run run.rb you get:

$ ruby run.rb 
 INFO test: started script
 INFO test: in do_something
hi!
 INFO test: finishing

和磁盘上名为logtest.log的日志文件.

and a log file named logtest.log on disk.

这篇关于在Ruby应用程序中正确使用Log4r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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