A slow query that only shows up in production is annoying, because by the time you run EXPLAIN yourself the problem has moved. auto_explain comes with PostgreSQL and logs the plan at the moment it happens.
LOAD 'auto_explain';
SET auto_explain.log_min_duration = '250ms';
SET auto_explain.log_analyze = true;
That is the session version, and the docs say you must be a superuser to use LOAD. Any statement that runs 250 ms or longer now gets its plan written to the server log. A value of 0 logs every plan and -1, the default, logs nothing.
To have it everywhere, preload it in postgresql.conf:
session_preload_libraries = 'auto_explain'
auto_explain.log_min_duration = '3s'
The caveat is log_analyze. With it on, per-node timing is measured for every statement, not just the slow ones, and the docs warn this can have an extremely negative impact on performance. Setting auto_explain.log_timing to off reduces the cost, at the price of less detail. auto_explain.log_buffers only does something when log_analyze is on, and auto_explain.sample_rate lets you explain only a fraction of statements.
The docs show what the result looks like. With log_min_duration at 0 and log_analyze on, a query against pg_class and pg_index logs a line like LOG: duration: 3.651 ms plan:, followed by the query text and the plan with actual times.
A few more parameters from that page: auto_explain.log_format accepts text, xml, json and yaml, with text as default. auto_explain.log_nested_statements is off by default, so statements inside functions aren’t logged until you turn it on. auto_explain.log_verbose is the same as the VERBOSE option of EXPLAIN. Only superusers can change these settings.
Further reading: auto_explain