Alexander Sung
Alexander Sung

Reputation: 325

Most efficient way to add additional logging to many methods in ruby?

I have a plain ruby app where I want to implement an option to launch the app in debug mode, where I add additional logging to all database query methods, outputting the query string and time taken.

When launched in debug mode, a global variable $debug_mode will be set to true.

My first thought is to create a method that takes a block of code and logs the appropriate data, basically:

def debug(query_string)
  if $debug_mode
    start_time = Time.now
    yield
    time_elapsed = Time.now - start_time
    log time_elapsed
    log query_string
  else
    yield
  end
end

and then, wrap every block of code I want to output additional logging with this method.

A few concerns:

I can't help but feel like there's a better way to accomplish this.

Any tips and suggestions are greatly appreciated.

Thank you.

Upvotes: 1

Views: 43

Answers (1)

Shelvacu
Shelvacu

Reputation: 4362

Do not worry about the extra time the conditionals will take, any difference will be dwarfed by SQL queries. If you're that concerned about speed you should be writing in C, not ruby.

This is just fine design, the only things I would change is to use $DEBUG instead of $debug_mode because $DEBUG can be set from the command line and is already a standard.

Also, you may at some point want the result of the yield, so you could do something like:

def debug(query_string)
  if $DEBUG
    start_time = Time.now
    result = yield
    time_elapsed = Time.now - start_time
    log time_elapsed
    log query_string
    return result
  else
    return yield
  end
end

Upvotes: 2

Related Questions