Search code examples
pythonloggingpgadmin-4audit-trail

How to log current pgAdmin user or current DB user to file?


I want to have an audit trail on pgAdmin-4 (version 3.0), about which user run which query. I have set the configuration of pgAdmin to show the needed log, however it doesn't show the currently connected pgAdmin user nor current DB user. It only show the logger name which is pgadmin. Example of log:

2019-04-15 11:38:56,769: SQL    pgadmin:    Execute (async) for server #8 - CONN:2363996 (Query-id: 780067):
select * from my_table limit 5;
2019-04-15 11:38:57,135: SQL    pgadmin:    Polling result for (Query-id: 780067)
2019-04-15 11:38:57,136: SQL    pgadmin:    Execute (dict) for server #8 - DB:mydb_development (Query-id: 5477805):

Here is the configuration of pgAdmin that I have tried (config_local.py):

DEBUG = False
CONSOLE_LOG_LEVEL = 30
FILE_LOG_LEVEL = 25
CONSOLE_LOG_FORMAT = '%(asctime)s: %(levelname)s\t%(name)s:\t%(message)s'
FILE_LOG_FORMAT = '%(asctime)s: %(levelname)s\t%(name)s:\t%(message)s'
LOG_FILE = '/var/log/pgadmin/pgadmin4.log'

What I want is to be able to print currently used pgAdmin user or if it can't be done, just print current DB user.

Example:

2019-04-15 11:38:56,769: SQL    my_pgadmin_user:    Execute (async) for server #8 - CONN:2363996 (Query-id: 780067):
select * from my_table limit 5;

or

2019-04-15 11:38:56,769: SQL    my_postgres_user:   Execute (async) for server #8 - CONN:2363996 (Query-id: 780067):
select * from my_table limit 5;

Any help is appreciated. Thanks


Solution

  • I ended up modifying pgadmin code on file pgadmin4/pgadmin/utils/driver/psycopg2/connection.py to show the DB role.

    Method name: execute_async Changes

            d = self.conn.get_dsn_parameters()
    
            current_app.logger.log(
                30,
                u"Execute (async) by {db_user} for server #{server_id} - {conn_id} (Query-id: "
                u"{query_id}):\n{query}".format(
                    db_user=d['user'],
                    server_id=self.manager.sid,
                    conn_id=self.conn_id,
                    query=query.decode('utf-8'),
                    query_id=query_id
                )
            )