Skip to content

Writing your own adapter

rudionrails edited this page Dec 15, 2014 · 5 revisions

Writing Your Own Adapter

When writing an own adapter, you need to inherit form the Yell::Adapters::Base class. It will provide you with the required API and provides the following methods:

write: Handle the log event
setup: Use that to initialize the adapter (optional)
close: Close the file or database handle (optional)

To connect it with Yell, you will need to call register on the Yell::Adapters module.

The following example will demonstrate how to define and register a simple adapter that prints messages to STDOUT:

require 'yell'

class MyAdapter < Yell::Adapters::Base
  # Provides us with the :format method
  include Yell::Helpers::Base
  include Yell::Helpers::Formatter

  # Setup is called in your adapters initializer. You are not required to
  # define this method if you have no need for special settings. However, here 
  # it's used to set the initial message format.
  setup do |options|
    self.format = options[:format]
  end

  # Defining write is mandatory. It's the main adapter method and receives the log 
  # event. Here, we use the already set `format` (in the setup) to get a pretty
  # message out of the log event. Then, we simply print it to `STDOUT`.
  write do |event|
    message = format.call(event)

    STDOUT.puts message
  end

  # Close is reserved for closing a file handle or database connection - it takes no 
  # arguments. You are not required to define this method if you have no need for it. 
  close do
    # ... nothing to close ...
  end
end

# Register the newly written adapter with Yell
Yell::Adapters.register :my_adapter, MyAdapter

Now we can use this adapter just like any other:

logger = Yell.new :my_adapter
logger.info "Hello World"
#=> "2012-02-29T09:30:00+01:00 [ INFO] 65784 : Hello World!"

# Since we included the :format helper, we can use it like so:
logger = Yell.new :my_adapter, :format => Yell::BasicFormat
logger.info "Hello World"
#=> "I, 2012-02-29T09:30:00+01:00 : Hello World!"

# Also, the block syntax
logger = Yell.new do |l|
  l.adapter :my_adapter, :format => Yell::BasicFormat
end
logger.info "Hello World"
#=> "I, 2012-02-29T09:30:00+01:00 : Hello World!"