How to set application_name for postgres connections?
Asked Answered
M

6

34

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)?

Marcusmarcy answered 19/5, 2015 at 9:50 Comment(0)
G
40

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/

Garderobe answered 19/5, 2015 at 10:3 Comment(1)
@Gajus: I think that's only for libpq. JDBC still uses ApplicationName, it seemsPetty
K
27

Use set command:

set application_name to my_application;
Krypton answered 19/5, 2015 at 9:57 Comment(0)
S
8

For those using normal connection string and not jdbc:

postgresql://other@localhost/otherdb?application_name=myapp
Sarracenia answered 30/5, 2022 at 5:57 Comment(1)
Similar to: stackoverflow.com/a/15691283Avaricious
A
7

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.

Adroit answered 19/5, 2015 at 10:1 Comment(0)
C
4

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")
Chessman answered 8/4, 2020 at 7:20 Comment(0)
H
3

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

PGPoolingDataSource ds = new PGPoolingDataSource();
ds.setApplicationName(applicationName);
Handel answered 21/8, 2018 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.