Pg: Logger or output of raw SQL generated

Created on 2 Feb 2015  路  6Comments  路  Source: go-pg/pg

I've started migrating my project from beego ORM to use pg.v2. So far, it's been fantastic and handles some of few PostgreSQL issues I've had like UUID and Array support. Is there a way to output the raw generated SQL?

Most helpful comment

As it mentioned in wiki it also can be done this way:

type dbLogger struct { }

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

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

db := pg.Connect(&pg.Options{...})
db.AddQueryHook(dbLogger{})

All 6 comments

No, but in development environment you can adjust PostgreSQL to log all queries:

log_statement = 'all'
log_min_duration_statement = 0

Then postgresql-9.4-main.log will contain generated SQL. Is it enough for your needs?

That works for now. Thanks.

As it mentioned in wiki it also can be done this way:

type dbLogger struct { }

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

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

db := pg.Connect(&pg.Options{...})
db.AddQueryHook(dbLogger{})

When I try that, I get this:
cannot use dbLogger literal (type dbLogger) as type pg.QueryHook in argument to db.baseDB.AddQueryHook: dbLogger does not implement pg.QueryHook (wrong type for AfterQuery method) have AfterQuery(context.Context, *pg.QueryEvent) error want AfterQuery(*pg.QueryEvent)

This seems to work when trying to AfterQuery method. I haven't worked out the BeforeQuery method yet:

`type dbLogger struct{}

func (d dbLogger) AfterQuery(q *pg.QueryEvent) {
fmt.Println(q.FormattedQuery())
return
}

db := pg.Connect(&pg.Options{...})
db.AddQueryHook(dbLogger{})`

@PhillyWebGuy you likely have an incorrect import. Make sure you have imported:

"github.com/go-pg/pg/v10"
not
"github.com/go-pg/pg"

Was this page helpful?
0 / 5 - 0 ratings

Related issues

NinaLeven picture NinaLeven  路  6Comments

bobobo1618 picture bobobo1618  路  3Comments

m-kad picture m-kad  路  3Comments

AbooJan picture AbooJan  路  5Comments

l0gicgate picture l0gicgate  路  5Comments