casbin / casbin-pg-adapter

A go-pg adapter for casbin
https://github.com/casbin/casbin
Apache License 2.0
38 stars 28 forks source link

[Question] Logging all SQL Queries #20

Closed arafat-java closed 3 years ago

arafat-java commented 3 years ago

We are using casbin-pg-adapter for our policies storage to DB I would like to log all the queries that are fired to the DB. How can I do that?

pckhoi commented 3 years ago

Easiest thing one can do is to configure Postgres to log statements to stdout. I use this script:

#!/bin/sh
set -x

PGCONF=/var/lib/postgresql/data/postgresql.conf
sed -i "s/#log_statement = 'none'.*/log_statement = 'all'/g" $PGCONF
arafat-java commented 3 years ago

I've been using AWS RDS so that'll be a bit difficult for me

pckhoi commented 3 years ago

There is also go-pg query hook for this purpose:

type dbLogger struct{}

func (d dbLogger) BeforeQuery(ctx context.Context, q *pg.QueryEvent) (context.Context, error) {
    fmt.Println(q.FormattedQuery())
    return ctx, nil
}

func (d dbLogger) AfterQuery(ctx context.Context, q *pg.QueryEvent) error {
    return nil
}

db := pg.Connect(opts)
db.AddQueryHook(dbLogger{})
arafat-java commented 3 years ago

Thanks @pckhoi Works perfectly for me

arafat-java commented 3 years ago

Closing this out