Asad Iqbal
Asad Iqbal

Reputation: 3321

How should I log in ruby with minimum assumptions about the calling code

In java/jvm, we have slf4j which can be included without making any assumptions about the logging implementation. How can I achieve something similar in a ruby library/gem?

Upvotes: 0

Views: 89

Answers (1)

Holger Just
Holger Just

Reputation: 55768

There is a pretty common pattern in various ruby logger implementations to mimic the method interface of the standards library Logger, namely

  • the logger object responds to the methods debug, info, warn, error, fatal where you can pass a string containing the log message. Many logger implementations also allow to pass a block (which returns the log message) rather than an actual string
  • You also generally have an add method where you can pass a numeric log severity and the log message.

In your code, you can generally expect that all logger implementations implement at least this interface. You can then allow users of your code to provide their own logger object (which should implement those methods) which you can then use. This pattern is called dependency injection

Generally, in Ruby, you don't care about actual types of a given object. You just assume that is responds to messages send to it ("methods called"). As such, you don't need to care about a specific logger implementation, but just that it implements the expected interface. In Ruby, this is often called duck typing.

Upvotes: 2

Related Questions