Home > Back-end >  Logger default for class and new file for subclasses
Logger default for class and new file for subclasses

Time:09-21

module Modelname
  class ModelClass
     def logger
      @logger ||= Logger.new($stdout)
     end
  end
end

OtherCLass < ModelClass

How to ModelClass have default logger and OtherClass(Subclass) have custom logger in a file like otherclass.log

CodePudding user response:

You tell ruby to do exactly what you need. But beware, multiple loggers on the same file will not play nice with each other, so you'd better set the logger on the class object.

class ModelClass
  def logger
    self.class.logger
  end

  def self.logger
    @logger ||= begin
      target = self == ModelClass ? STDOUT : "#{name}.log"
      Logger.new(target)
    end
  end
end

You will have one logger per class, and all of them will go to files except the base class, which will go to STDOUT.

But why being so complex? You could just write all of them to files, and then tail -f YourFile.log to see the log you want on stdout.

  • Related