Skip to content

Instantly share code, notes, and snippets.

@elhu
Forked from archiloque/app.rb
Last active February 11, 2016 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elhu/fa99c1bfbf347d6eb0d8 to your computer and use it in GitHub Desktop.
Save elhu/fa99c1bfbf347d6eb0d8 to your computer and use it in GitHub Desktop.
Example of logging queries
require 'sinatra/base'
require 'sequel'
require 'logger'
# Add hooks in sequel logging since it's called for each query
module Sequel
class Database
# Alias a method so we can override it but still call the original
alias :log_yield_old :log_yield
# This method is called for each query so we can use it to count
def log_yield(sql, args=nil, &block)
Thread.current[:queries_count] += 1
log_yield_old(sql, args, &block)
end
# Alias a method so we can override it but still call the original
alias :log_duration_old :log_duration
# This method is called to measure duration so we can use it to measure duration
def log_duration(duration, message)
Thread.current[:queries_duration] += duration
log_duration_old(duration, message)
end
end
end
class App < Sinatra::Base
DB = Sequel.sqlite '', :loggers => [Logger.new(STDOUT)]
# Hook called before each call
before do
# Initialize the thread local variables
Thread.current[:queries_count] = 0
Thread.current[:queries_duration] = 0
end
# Hook called after each call
after do
# Set the headers
headers['X-QUERIES-COUNT'] = Thread.current[:queries_count].to_s
headers['X-QUERIES-DURATION'] = Thread.current[:queries_duration].to_s
# Clean the thread local variables
Thread.current[:queries_count] = nil
Thread.current[:queries_duration] = nil
end
# This is my service, you'll be impressed
get '/' do
# Simple query that doesn't need any table
DB.run "SELECT 'OK'"
'OK'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment