Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log correctly inside my Ruby gem?

Tags:

ruby

Currently I'm using puts, but I'm sure that's not the correct answer. How do I correctly setup a logger, inside my gem, to output my internal logging instead of puts?

like image 882
Kamilski81 Avatar asked Jul 30 '12 20:07

Kamilski81


People also ask

How do gems work in Ruby?

Gems can be used to extend or modify functionality in Ruby applications. Commonly they're used to distribute reusable functionality that is shared with other Rubyists for use in their applications and libraries. Some gems provide command line utilities to help automate tasks and speed up your work.

Which is the command used to list all the gems available in Ruby?

The Gem command is included with Ruby 1.9+ now, and is a standard addition to Ruby pre-1.9. Because local_gems relies on group_by , it returns a hash of the gems, where the key is the gem's name, and the value is an array of the gem specifications.

What does gem install do?

What does gem install do? gem install , in its simplest form, does something kind of like this. It grabs the gem and puts its files into a special directory on your system. You can see where gem install will install your gems if you run gem environment (look for the INSTALLATION DIRECTORY: line):

What is gem in Ruby on Rails?

Gems in Rails are libraries that allow any Ruby on Rails developer to add functionalities without writing code. You can also call Ruby on Rails gems as plugins for adding features. A Ruby gem enables adding features without creating the code again and again.


2 Answers

The most flexible approach for users of your gem is to let them provide a logger rather than setting it up inside the gem. At its simplest this could be

class MyGem
  class << self
    attr_accessor :logger
  end
end

You then use MyGem.logger.info "hello" to log messages from your gem (you might want to wrap it in a utility method that tests whether a logger is set at all)

Users of your gem can then control where messages get logged to (a file, syslog, stdout, etc...)

like image 53
Frederick Cheung Avatar answered Oct 14 '22 17:10

Frederick Cheung


You can keep the logger in your top-level module. Allow user's to set their own logger but provide a reasonable default for those who don't care to deal with logging. For e.g.

module MyGem
  class << self
    attr_writer :logger

    def logger
      @logger ||= Logger.new($stdout).tap do |log|
        log.progname = self.name
      end
    end
  end
end

Then, anywhere within your gem code you can access the logger. For e.g.

class MyGem::SomeClass

  def some_method
    # ...
    MyGem.logger.info 'some info'
  end

end

References:

  • Using the Ruby Logger
  • Logger
like image 35
Dwayne Crooks Avatar answered Oct 14 '22 16:10

Dwayne Crooks