7

我真的错过了一些明显的东西,但是我在我的 Ruby 应用程序中一般使用 Log4r 时遇到了麻烦。我可以毫无问题地登录,但是我设置它的方式似乎很笨重。我基本上将完整路径传递给文件名以登录我的应用程序中的每个类。被调用的 ruby​​ 脚本从 ARGV 中的一个参数中提取日志文件,然后将其传递并设置在我在 ruby​​ 中调用的每个类中。在每个类中,我使用 patternFormatter 将类/文件名插入到日志语句中。

有没有更好的方法来完成这项工作?感觉无论我怎么想,都需要在我的 ruby​​ 应用程序中向每个类传递一些东西。我可以在 yaml 配置文件中设置日志文件,但是我也会将配置文件传递给每个类。

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

谢谢!

4

2 回答 2

14

I'm the maintainer of log4r,

For individual scripts (different .rb files), you could approach this in a few different ways (fitting, I know), first, be mindful that the features I'm covering here are available in >= 1.1.4.

One way would be to set a different PatternFormatter string per script (if you create a yaml or xml configuration file, you can specify different patterns on a per class name basis).

Another way would be to use one of GDC, NDC or MDC in a PatternFormatter.

GDC will set a "Global Diagnostic Context" which is to say, it's a value that is available from all threads running a script. You can use it by putting %g in the pattern and setting the value via GDC.set(String) for more detailed information, see: http://log4r.rubyforge.org/manual.html

NDC and MDC are Nested and Mapped Diagnostic Contexts respectively. The pattern for these is to use %x and %X{Symbol|Object}, and to set them via NDC.set(String) and MDC.put(Symbol|Object, Object)

Yet another way would be to use the Pattern %t, which prints out the filename and line number of where the call was made.

The trade off between each of these methods is that they are progressively more expensive in CPU resource use. I tend to first use GDC for the sort of thing you're asking for.

于 2010-12-28T21:30:10.657 回答
12

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

运行.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')

类a.rb:

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

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

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

logtest.log和一个在磁盘上命名的日志文件。

于 2010-03-18T19:54:50.873 回答