schedule · 2 min read

How to set application_name for psql command line utility?

link
Part of series
Postgres Tips

The application_name configuration is used to identify a database client from postgres backend. It is extremely useful in debugging client issues and connection resource consumption by client using the application_name.

Backend servers use connection string to set application_name using the database abstraction libraries like sqlalchemy. For example,

engine = create_engine("postgresql://scott:tiger@localhost:5432/
postgres?application_name=user_service")

When connecting to postgres database using psql command line utility psql sets a default application_name “psql”. we can inspect application name from sql shell like below,

postgres=# show application_name;
 application_name 
------------------
 psql
(1 row)

-- connections used by different clients
postgres=# select application_name, count(*) from pg_stat_activity group by application_name;
             application_name              | count 
-------------------------------------------+-------
 psql                                      |     1
                                           |     5
(2 rows)

set application_name for psql

Method 1 - environment variable

 export PGAPPNAME=mylocalpgshell

➜  pgdb psql -h localhost -p 5444 -U postgres -d postgres                                           
psql (12.2, server 12.1)
Type "help" for help.

postgres=# show application_name;
 application_name 
------------------
 mylocalpgshell
(1 row)

postgres=# select application_name, count(*) from pg_stat_activity group by application_name;
             application_name              | count 
-------------------------------------------+-------
                                           |     5
 mylocalpgshell                            |     1
(2 rows)

Method 2 - db connection string

➜  psql -h localhost -p 5444 -U postgres \
-d 'dbname=postgres application_name=mylocalpsqlshell'

postgres=# show application_name;
 application_name 
------------------
 mylocalpsqlshell
(1 row)

postgres=# select application_name, count(*) from pg_stat_activity group by application_name;
             application_name              | count 
-------------------------------------------+-------
 mylocalpsqlshell                          |     1
                                           |     5
(2 rows)

If you find this article useful, do comment below and share this article with others.

link
Part of series
Postgres Tips

Subscribe to my newsletter

Get new posts delivered straight to your inbox.