I am writing a backend in go for an angular application. I want to log for every request how many database queries were executed.
For this, I want to increment an integer every time sql.Exec is called. How do I do this without manually adding it to every single place I use sql.Exec? Or is there a better way to do this?
How do I do this without manually adding it to every single place I use sql.Exec?
Wrap your SQL access object. For example:
type MyDB struct {
*sql.DB
count int
}
func (db *MyDB) Exec(query string, args ...interface{}) (sql.Result,error) {
db.count++
return db.DB.Exec(query, args...)
}
Then use your wrapped type everywhere. This will (probably) mean updating a lot of code to use an interface, rather than a *sql.DB
variable.
The only other option is to write a wrapper around the SQL driver (rather than the client). But you'd use the same approach. This method requires a bit more understanding of Go's sql
internals.
How do I do this without manually adding it to every single place I use sql.Exec?
Not at all. Go offers no magic. If you want things done you must do them.