Why a Go Query Logger Can Put Personal Data in Postgres Server Logs
You would expect a query logger in your Go service to write to your service's logs. A "helpful" one that runs EXPLAIN on slow queries can also copy email addresses into the Postgres server log, a file that may have different readers, shipping rules and retention.
The cause is a small convenience: replacing $1 with the real value before sending the SQL back to the database. I reproduced everything below with PostgreSQL 18.7, Go 1.27.4 and pgx 5.13.0.
Filling in the placeholders turns data into SQL text
pgx lets you hook every query with a QueryTracer. A tempting slow-query logger grabs the SQL and arguments, pastes one into the other, and asks Postgres for the plan:
// Don't do this.
func inline(sql string, args []any) string {
for i := len(args) - 1; i >= 0; i-- {
v := strings.ReplaceAll(fmt.Sprint(args[i]), "'", "''")
sql = strings.ReplaceAll(sql, fmt.Sprintf("$%d", i+1), "'"+v+"'")
}
return sql
}
// Called from TraceQueryEnd when a query was slow.
rows, _ := side.Query(ctx, "EXPLAIN "+inline(sql, args))
plan, err := pgx.CollectRows(rows, pgx.RowTo[string])
Your original query sent the SQL and the values separately. This second one sends a new SQL string with the personal data baked in. Postgres has no way of knowing that the quoted email used to be a parameter.
It is also an injection bug. If the value for $2 contains the text $1, the next pass substitutes inside it, quotes and all, and user input can break out of its string.
Default settings are enough when the EXPLAIN fails
A failing statement gets written to the server log out of the box, because log_min_error_statement defaults to ERROR, and hand-rolled inlining fails easily.
Take a query with an optional cursor, where the second argument is a nil *int64:
var before *int64
err := conn.QueryRow(ctx,
`SELECT count(*) FROM users
WHERE email = $1 AND ($2::bigint IS NULL OR id < $2)`,
"[email protected]", before,
).Scan(&n)
The real query works, but the logger's copy fails because fmt.Sprint turns that nil pointer into the string <nil>. With every logging setting reset to its default, the server wrote this:
ERROR: invalid input syntax for type bigint: "<nil>" at character 79
STATEMENT: EXPLAIN SELECT count(*) FROM users WHERE email = '[email protected]' AND ('<nil>'::bigint IS NULL OR id < '<nil>')
One broken argument drags all the others into the log with it. The application sees only an error from a diagnostic side query, which is exactly the sort of thing people ignore.
A successful inlined EXPLAIN can be logged as well, if log_statement or log_min_duration_statement catches it. With a high duration threshold a quick EXPLAIN may slip under, so a clean log on a quiet day proves little.
Real bind parameters get logged too, but you can switch that off
Quick detour, because this surprised people long before any tracer got involved. With log_min_duration_statement = 0 and parameter settings left alone, an ordinary parameterised query produced:
LOG: duration: 1.131 ms bind stmtcache_517d...: SELECT count(*) FROM users WHERE email = $1
DETAIL: Parameters: $1 = '[email protected]'
That is log_parameter_max_length at its default of -1, meaning log bind parameters in full. Setting it to 0 removed the DETAIL line in my test.
That setting cannot redact literals in the statement itself. With it at 0, the inlined EXPLAIN still logged the address. So did pgx's QueryExecModeSimpleProtocol, which interpolates arguments on the client:
LOG: duration: 0.599 ms statement: SELECT count(*) FROM users WHERE email = '[email protected]'
pgx quotes those values properly, unlike our homemade function, but they still end up in the log. If you enabled simple protocol for a proxy or pooler, check whether you still need it.
Ask for a generic plan and send no values at all
PostgreSQL 16 added EXPLAIN (GENERIC_PLAN), which accepts a statement with $1 still in it. Neatly, the logger no longer needs the arguments, so it doesn't even keep them.
package main
import (
"context"
"errors"
"log/slog"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type queryKey struct{}
type queryStart struct {
sql string
at time.Time
}
type planTracer struct {
side *pgxpool.Pool // a separate pool with no tracer
slow time.Duration
}
func (t *planTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
return context.WithValue(ctx, queryKey{}, queryStart{d.SQL, time.Now()})
}
func (t *planTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, _ pgx.TraceQueryEndData) {
q, ok := ctx.Value(queryKey{}).(queryStart)
if !ok || time.Since(q.at) < t.slow {
return
}
// The slow query's context may already be dead, so detach and re-limit.
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
plan, err := genericPlan(ctx, t.side, q.sql)
if err != nil {
slog.WarnContext(ctx, "slow query, no plan", "sql", q.sql, "err", err)
return
}
slog.WarnContext(ctx, "slow query", "sql", q.sql, "plan", plan)
}
func genericPlan(ctx context.Context, pool *pgxpool.Pool, sql string) (string, error) {
// The simple protocol runs every statement in the string, so allow only one.
if strings.Contains(sql, ";") {
return "", errors.New("SQL contains a semicolon")
}
conn, err := pool.Acquire(ctx)
if err != nil {
return "", err
}
defer conn.Release()
results, err := conn.Conn().PgConn().Exec(ctx, "EXPLAIN (GENERIC_PLAN) "+sql).ReadAll()
if err != nil {
return "", err
}
var plan strings.Builder
for _, result := range results {
for _, row := range result.Rows {
plan.Write(row[0])
plan.WriteByte('\n')
}
}
return plan.String(), nil
}
The code drops down to PgConn().Exec because we want the text sent as it is, with placeholders and no bound arguments. The plan that comes back says Index Cond: (email = $1). The inlined version printed the actual address there, so it was leaking into the application log as well.
Without the semicolon check, a two-statement string would have only its first statement explained, and the second would run. The check is deliberately blunt and also rejects harmless semicolons inside strings.
There are trade-offs and limits:
- A generic plan can differ from the plan chosen for your particular values, especially with skewed data.
GENERIC_PLANcannot be combined withANALYZE, so there are no real timings.- Some placeholders need an explicit cast before Postgres can infer a type, and some statements cannot be explained at all.
- The tracer runs in the request path. On a busy service, rate-limit it.
- Values you concatenated into the original SQL are still there.
Errors and comments can still carry the data
A well-behaved logger does not make the server log free of personal data. Postgres error messages often quote the offending value. With parameterised queries and default error settings, I got:
ERROR: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=([email protected]) already exists.
STATEMENT: INSERT INTO users (email) VALUES ($1)
ERROR: invalid input syntax for type integer: "[email protected]"
STATEMENT: SELECT $1::text::int
Setting log_error_verbosity = terse removes the DETAIL line, along with hints and context you may miss during an incident. The second example is unaffected because the value is in the primary error message.
SQL comments are another route. If a tracer or wrapper prefixes queries with something like /* [email protected] */ for correlation, that comment is part of the statement and is logged with it. Use an opaque request ID, and remember that it may still be linkable to a person.
Test your own server with a fake address
Check the settings first:
SELECT name, setting
FROM pg_settings
WHERE name IN (
'log_statement',
'log_min_duration_statement',
'log_min_error_statement',
'log_parameter_max_length',
'log_parameter_max_length_on_error',
'log_error_verbosity'
);
Then, on a test system:
- Pick a unique canary address that appears nowhere else.
- Send it through a normal request, a deliberately slow one, and one that triggers a database error.
- Search the Postgres log, the application log and wherever either gets shipped.
To stop routine bind-parameter logging, a suitably privileged role can run:
ALTER SYSTEM SET log_parameter_max_length = 0;
ALTER SYSTEM SET log_parameter_max_length_on_error = 0; -- already the default
SELECT pg_reload_conf();
Roles or databases can carry their own overrides, so run the check as your application's role. My view is that you should still treat the server log as holding personal data: limit who reads it and how long it lives. Data minimisation and storage limitation in Article 5 of the UK GDPR don't stop applying because the copy was made by a debugging helper.