How to log PostgreSQL queries?

Better Stack Team
Updated on November 23, 2022

If you would like to log all PostgreSQL queries into a file, you can do that by changing few settings int the configuration file

Open the data/postgresql.conf file and change the following settings:

  • #log_directory = 'pg_log’ change to log_directory = 'pg_log’
  • #log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log’ change to log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
  • #log_statement = 'none’ change to log_statement = 'all’
  • #logging_collector = off change to logging_collector = on
  • Run the following statement:
SELECT set_config('log_statement', 'all', true);
  • Then restart the PostgreSQL server
sudo service postgresql restart

Now, you can find the logs in the following directory /var/lib/pgsql/9.2/data/pg_log/

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github