Skip to content

Instantly share code, notes, and snippets.

@hilotter

hilotter/app.rb Secret

Created September 21, 2020 09:43
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 hilotter/0db41ff062d44e7ac5503e94b4f68bcb to your computer and use it in GitHub Desktop.
Save hilotter/0db41ff062d44e7ac5503e94b4f68bcb to your computer and use it in GitHub Desktop.
sinatra + mysql2でNewRelicのDB分析を有効にする
require 'sinatra'
require 'newrelic_rpm'
require 'mysql2'
require 'mysql2-cs-bind'
class Mysql2ClientWithNewRelic < Mysql2::Client
def initialize(*args)
super
end
def query(sql, *args)
callback = -> (result, metrics, elapsed) do
NewRelic::Agent::Datastores.notice_sql(sql, metrics, elapsed)
end
op = sql[/^(SELECT|INSERT|UPDATE|DELETE|BEGIN|COMMIT|ROLLBACK)/i] || 'other'
table = sql[/\bchair|estate\b/] || 'other'
NewRelic::Agent::Datastores.wrap('MySQL', op, table, callback) do
super
end
end
end
class App < Sinatra::Base
helpers do
def db_info
{
host: ENV.fetch('MYSQL_HOST', '127.0.0.1'),
port: ENV.fetch('MYSQL_PORT', '3306'),
username: ENV.fetch('MYSQL_USER', 'isucon'),
password: ENV.fetch('MYSQL_PASS', 'isucon'),
database: ENV.fetch('MYSQL_DBNAME', 'isuumo'),
}
end
def db
Thread.current[:db] ||= Mysql2ClientWithNewRelic.new(
host: db_info[:host],
port: db_info[:port],
username: db_info[:username],
password: db_info[:password],
database: db_info[:database],
reconnect: true,
symbolize_keys: true,
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment