How to set application_name for postgres connections?

37.5k views Asked by At

I'm using tomcat connection pool org.apache.tomcat.jdbc.pool.DataSource. The connections appear in my database pg_stat_activity with empty application_name.

How could I set that application name in my java app, so I know where each connection comes from (as there will be multiple applications accessing the same db)?

6

There are 6 answers

1
Cristian Sevescu On BEST ANSWER

You could specify the application name in the connection string.
Documentation [here][1].

Example:

jdbc:postgresql://localhost:5435/DBNAME?ApplicationName=MyApp

Take care: the param names are case sensitive. [1]: https://jdbc.postgresql.org/documentation/use/

1
Matteo On

For those using normal connection string and not jdbc:

postgresql://other@localhost/otherdb?application_name=myapp
0
Krishna On

If you're using Python library psycopg2, here's how you can do

import psycopg2    
psycopg2.connect(host=host_ip, database=db_name, user=user, password=db_pwd, application_name="Python Local Test Script")
0
Mike On

If you want to set programmatically, the PostgreSQL drivers also have a method you can call:

PGPoolingDataSource ds = new PGPoolingDataSource();
ds.setApplicationName(applicationName);
0
klin On

Use set command:

set application_name to my_application;
0
AudioBubble On

You can add this to the JDBC URL that you use in your connection pool definition:

jdbc:postgresql://localhost/postgres?ApplicationName=my_app

If you want to change it dynamically e.g. to reflect different modules inside your application, the you can use the SET command as shown by klin.