Properly using Log4r in Ruby Application

北城以北 提交于 2019-12-03 07:20:17

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
  def do_something
    logger = Log4r::Logger['test']
    logger.info('in do_something')
    puts 'hi!'
  end
end

and when you run run.rb you get:

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

and a log file named logtest.log on disk.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!