Ruby - share logger instance among module/classes

后端 未结 9 1733
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 06:45

Working on a little Ruby script that goes out to the web and crawls various services. I\'ve got a module with several classes inside:

module Crawler
  class          


        
9条回答
  •  不思量自难忘°
    2020-12-04 07:14

    Although an old question, I thought it worthwhile to document a different approach.

    Building on Jacob's answer, I would suggest a module that you can add in as and when needed.

    My version is this:

    # saved into lib/my_log.rb
    
    require 'logger'
    
    module MyLog
    
      def self.logger
        if @logger.nil?
          @logger = Logger.new( STDERR)
          @logger.datetime_format = "%H:%M:%S "
        end
        @logger
      end
    
      def self.logger=( logger)
        @logger = logger
      end
    
      levels = %w(debug info warn error fatal)
      levels.each do |level|
        define_method( "#{level.to_sym}") do |msg|
          self.logger.send( level, msg)
        end
      end
    end
    
    include MyLog
    

    I have this saved into a library of handy modules, and I would use it like this:

    #! /usr/bin/env ruby
    #
    
    require_relative '../lib/my_log.rb'
    
    MyLog.debug "hi"
    # => D, [19:19:32 #31112] DEBUG -- : hi
    
    MyLog.warn "ho"
    # => W, [19:20:14 #31112]  WARN -- : ho
    
    MyLog.logger.level = Logger::INFO
    
    MyLog.logger = Logger.new( 'logfile.log')
    
    MyLog.debug 'huh'
    # => no output, sent to logfile.log instead
    

    I find this a lot easier and more versatile than other options I've looked at so far, so I hope it helps you with yours.

提交回复
热议问题