Skip to content

Instantly share code, notes, and snippets.

@hilotter

hilotter/app.rb Secret

Created Sep 21, 2020
Embed
What would you like to do?
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