Quantcast
Channel: Planet PostgreSQL
Viewing all articles
Browse latest Browse all 9948

Guillaume LELARGE: How to log superuser queries

$
0
0

A few weeks ago, one of my customers asked me if they could log all queries coming from superuser users. They have to make sure that none of their DBA could fire a query without that query being logged.

You can already log queries with the log_statement, or log_min_duration_statement GUCs. You can set these GUCs cluster-wide or for specific users. But there's a big issue here: the user can change the value of these GUCs, making it impossible to be sure everything they do is logged.

I first thought of writing a patch to handle this in PostgreSQL, but it also has a major issue: it won't be available for 9.0, the release they use. All new features are added to the development release, and I don't want to maintain a custom PostgreSQL release for anyone (that's too much burden). So, I came up with a nicer way of doing it.

PostgreSQL allows you to add hooks to the executor since 8.4. And you can use these hooks to know which queries are executed and by who. Actually, that's how pg_stat_statements works. So, all I needed to do was to create a small shared library that will add hooks to the executor. The hooks will check that the user executing a query is a superuser, and if that's true, log the query. Quite simple, here is the code of the hook:

static void
pgluq_log(const char *query)
{
    Assert(query != NULL);

    if (superuser())
        elog(log_level, "%s %s: %s", log_label, GetUserNameFromId(GetUserId()), query);
}

Of course, the library has more code than just that: to add/remove the hooks, to take care of two module GUCs (log level, and log prefix), but the most important stuff is on the pglug_log() function.

The module is available right now on github, and I intend to publish it via the pgxn.org website once my account will be approved. Docs are available here. It's compatible with PostgreSQL 8.4, 9.0, and 9.1.

Next thing I will do for this module is to add support for syslog. Right now, it only logs to the same location than PostgreSQL.


Viewing all articles
Browse latest Browse all 9948

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>