101 the datefile adapter

Rudolf Schmidt edited this page Jun 20, 2013 · 9 revisions

Yell 101 - How To: The Datefile Adapter

In many scenarios, you will want to have one file for each day, e.g. rollover of the log. This is where the Datefile adapter comes into place. A basic datefile adapter is defined as follows:

logger = Yell.new :datefile, 'development.log'

# The same logger defined within the block
logger = Yell.new do |l|
  l.adapter :datefile, 'development.log'

Although you have provided development.log as filename, by default, the adapter will replace it with development.YYYYMMDD.log, e.g. development.20121224.log.

Defining the Date Pattern (know your options)

The standard is a daily log rotate, but you are able to change that to your own likings. You only need to pass a :date_pattern option to the adapter, which will respect any possible string for Ruby's strftime method.

Example: Rotate the log every hour

Let's assume that Time.now results to 2012-12-24 15:00:30 +0100

logger = Yell.new do |l|
  l.adapter :datefile, 'development.log', :date_pattern => "%Y%m%d-%H"

logger.info "Hello World!"

The message would be logged into development.20121224-15.log. Any later hour will go into a new log file.

Example: Rotate the log every week

logger = Yell.new do |l|
  l.adapter :datefile, 'development.log', :date_pattern => "%Y-week-%V"

logger.info "Hello World!"

The message would be logged into development.2012-week-52.log

Automatic cleanup of the log directory

There is a - sort-of experimental - option that you can pass to keep your logiles in check:

logger = Yell.new do |l|
  l.adapter :datefile, 'development.log', :keep => 5

As usual, the datefile adapter will roll your files over, but this time the :keep option will cleanup any datefile logs (of the same pattern as the current one) and only hold on to the given number.

Symlink to the original filename

Another - sort of experimental - option is to have the originally given filename symlinked to the current timestamped filename.

logger = Yell.new do |l|
  l.adapter :datefile, 'development.log', :symlink => true

Now, when you start logging, the regular timestamped file will be created as well as a symlink to development.log from the above example.

ls -l

development.log -> development.20120629.log

Upon rollover, the symlink will be reset. This feature is helpful if you are running periodic log analytics (to fetch errors, for instance) and you don't want to tell that other script to use a different file depending on your date pattern.

If you want to know more, continue to How To: Different Adapters for Different Log Levels