Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Allow logging slow SQL queries to sentry/local logger

Oliver Günthercbb04e354149
diff --git a/config/initializers/log_slow_sql_queries.rb b/config/initializers/log_slow_sql_queries.rb
new file mode 100644
index 00000000000..dceec6f5584
--- /dev/null
+++ b/config/initializers/log_slow_sql_queries.rb
@@ -0,0 +1,30 @@
+OpenProject::Application.configure do
+ config.after_initialize do
+ slow_sql_threshold = OpenProject::Configuration.sql_slow_query_threshold.to_i
+ return if slow_sql_threshold == 0
+
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, start, finish, _id, data|
+ # Skip transaction that may be blocked
+ next if data[:sql].match(/BEGIN|COMMIT/)
+
+ # Skip smaller durations
+ duration = ((finish - start) * 1000).round(4)
+ next if duration <= slow_sql_threshold
+
+ payload = {
+ duration: duration,
+ time: start.iso8601,
+ cached: !!data[:cache],
+ sql: data[:sql],
+ }
+
+ sql_log_string = data[:sql].strip.gsub(/(^([\s]+)?$\n)/, "")
+ OpenProject.logger.warn "Encountered slow SQL (#{payload[:duration]} ms): #{sql_log_string}",
+ payload: payload,
+ # Hash of the query for reference/fingerprinting
+ reference: Digest::SHA1.hexdigest(data[:sql])
+ rescue StandardError => e
+ OpenProject.logger.error "Failed to record slow SQL query: #{e}"
+ end
+ end
+end
diff --git a/lib/open_project/configuration.rb b/lib/open_project/configuration.rb
index c919b5b9cc4..0fa9f9a8601 100644
--- a/lib/open_project/configuration.rb
+++ b/lib/open_project/configuration.rb
@@ -173,7 +173,10 @@ module OpenProject
'enterprise_trial_creation_host' => 'https://augur.openproject.com',
# Allow override of LDAP options
- 'ldap_auth_source_tls_options' => nil
+ 'ldap_auth_source_tls_options' => nil,
+
+ # Slow query logging threshold in ms
+ 'sql_slow_query_threshold' => 2000
}
@config = nil