0

I made a simple class to wrap native logger:

#logging.rb
require 'logger'

class Log

  def initialize(lname = 'log')
    @logger = Logger.new('logs/'+lname+'.txt')
    @logger.level = Logger::INFO
  end

  def Info(msg, print = true)
    @logger.info(msg)

    if print
      puts msg
    end
  end

  def Warning(msg, print = true)
    @logger.warn(msg)

    if print
      puts msg
    end
  end

end

and then I use it in a script like so

require_relative 'logging'
require_relative 'anotherclass'
@logger = Log.new("Mylog_"+Time.now.strftime('%Y-%m-%d_%H-%M-%S'))    
@logger.Info('Starting')

@anotherclass = AnotherClass.new()

This all works fine, but I would like to be able to use the same logger object in other classes, with the objective being the same log file will be appended to, instead of creating another file.

So if I make another class

#anotherclass.rb
require_relative 'logging'

class AnotherClass

    def initialize()
       Log.Info("Log to the same log file")
    end
end

How can I get it to use the previously created Log class?

SpeedOfRound
  • 1,210
  • 11
  • 26
  • 1
    Note: Ruby is a case-sensitive language and capital letters have specific meaning in terms of syntax. Variables and method names should be lower-case letters. Capitals indicate constants of the form `ClassName` or `CONSTANT_NAME`. – tadman Nov 14 '19 at 18:19
  • https://stackoverflow.com/questions/12573843/ruby-using-variables-between-classes may be helpful – Sara Fuerst Nov 14 '19 at 18:26
  • You can also create a class variable and make your classes subclasses of `Log` https://stackoverflow.com/questions/52570749/ruby-ability-to-share-a-single-variable-between-multiple-classes – Sara Fuerst Nov 14 '19 at 18:27
  • Passing the log class as a parameter was a solution I thought of, but seems really improper. Making other things subclasses of Log is definitely not proper, and also I'd rather not wrap my script in a class just for the sake of it. – SpeedOfRound Nov 14 '19 at 18:54

0 Answers0