Check the slow query in PostgreSQL

Enable or disable the slow query logging in PostgreSQL

Capture the slow queries with the help of the log_min_duration_statement parameter which defines the time taken by queries as more than the set time of this parameter. Suppose if we put 30 seconds then queries taking time more than 30 seconds is captured.

Enable slow query log to enable in PostgreSQL for Particular Database

Note: 0 value for parameter start logging all the queries

-- Capture all the SQL Queries running on database
ALTER DATABASE dbname SET log_min_duration_statement=0;

-- Capute only queries that take more than 10 seconds
ALTER DATABASE dbname SET log_min_duration_statement=10000;

Enable slow query log for all databases then update the configuration file:

log_min_duration_statement = 0

Or 

 -- 0 is used to capture all SQL's
Alter system set log_min_duration_statement=0;

-- capture queries taking time more 10 seconds
Alter system set log_min_duration_statement=10000;

--Reload configuration:
# SELECT pg_reload_conf();

Note: If you do not see any records, you may want to enable logging_collector = on 

Check the log file destination and format:

--methods for logging server messages, including stderr, csvlog, jsonlog, and syslog. On Windows, eventlog is also supported. Default stderr set.
show log_destination;

-- determines the directory in which log files will be created.
show log_directory;

-- this parameter sets the file names of the created log files.
show log_filename;

Disable the logging

ALTER DATABASE dbname SET log_min_duration_statement=-1;

Leave a Reply