Skip to content

Commit e50215c

Browse files
committed
Use custom logger for sql debug logging
1 parent b4606ff commit e50215c

File tree

10 files changed

+110
-57
lines changed

10 files changed

+110
-57
lines changed

api/api.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ func NewAPIWithVersion(ctx context.Context, globalConfig *conf.GlobalConfigurati
9898

9999
r.Route("/", func(r *router) {
100100
r.UseBypass(logger)
101+
r.Use(api.loggingDB)
101102
if globalConfig.MultiInstanceMode {
102103
r.Use(api.loadInstanceConfig)
103104
}
@@ -147,9 +148,10 @@ func NewAPIWithVersion(ctx context.Context, globalConfig *conf.GlobalConfigurati
147148

148149
if globalConfig.MultiInstanceMode {
149150
// Operator microservice API
150-
r.WithBypass(logger).With(api.verifyOperatorRequest).Get("/", api.GetAppManifest)
151+
r.WithBypass(logger).With(api.loggingDB).With(api.verifyOperatorRequest).Get("/", api.GetAppManifest)
151152
r.Route("/instances", func(r *router) {
152153
r.UseBypass(logger)
154+
r.Use(api.loggingDB)
153155
r.Use(api.verifyOperatorRequest)
154156

155157
r.Post("/", api.CreateInstance)

api/db_logger.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package api
2+
3+
import (
4+
"context"
5+
"net/http"
6+
7+
"github.com/jinzhu/gorm"
8+
gcontext "github.com/netlify/gocommerce/context"
9+
"github.com/netlify/gocommerce/models"
10+
)
11+
12+
func (a *API) loggingDB(w http.ResponseWriter, r *http.Request) (context.Context, error) {
13+
if a.db == nil {
14+
return r.Context(), nil
15+
}
16+
17+
log := getLogEntry(r)
18+
db := a.db.New()
19+
db.SetLogger(models.NewDBLogger(log))
20+
21+
return gcontext.WithDB(r.Context(), db), nil
22+
}
23+
24+
// DB provides callers with a database instance configured for request logging
25+
func (a *API) DB(r *http.Request) *gorm.DB {
26+
ctx := r.Context()
27+
return gcontext.GetDB(ctx)
28+
}

api/download.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,22 @@ const maxIPsPerDay = 50
1515
// DownloadURL returns a signed URL to download a purchased asset.
1616
func (a *API) DownloadURL(w http.ResponseWriter, r *http.Request) error {
1717
ctx := r.Context()
18+
db := a.DB(r)
1819
downloadID := chi.URLParam(r, "download_id")
1920
logEntrySetField(r, "download_id", downloadID)
2021
claims := gcontext.GetClaims(ctx)
2122
assets := gcontext.GetAssetStore(ctx)
2223

2324
download := &models.Download{}
24-
if result := a.db.Where("id = ?", downloadID).First(download); result.Error != nil {
25+
if result := db.Where("id = ?", downloadID).First(download); result.Error != nil {
2526
if result.RecordNotFound() {
2627
return notFoundError("Download not found")
2728
}
2829
return internalServerError("Error during database query").WithInternalError(result.Error)
2930
}
3031

3132
order := &models.Order{}
32-
if result := a.db.Where("id = ?", download.OrderID).First(order); result.Error != nil {
33+
if result := db.Where("id = ?", download.OrderID).First(order); result.Error != nil {
3334
if result.RecordNotFound() {
3435
return notFoundError("Download order not found")
3536
}
@@ -44,7 +45,7 @@ func (a *API) DownloadURL(w http.ResponseWriter, r *http.Request) error {
4445
return unauthorizedError("This download has not been paid yet")
4546
}
4647

47-
rows, err := a.db.Model(&models.Event{}).
48+
rows, err := db.Model(&models.Event{}).
4849
Select("count(distinct(ip))").
4950
Where("order_id = ? and created_at > ? and changes = 'download'", order.ID, time.Now().Add(-24*time.Hour)).
5051
Rows()
@@ -66,7 +67,7 @@ func (a *API) DownloadURL(w http.ResponseWriter, r *http.Request) error {
6667
return internalServerError("Error signing download").WithInternalError(err)
6768
}
6869

69-
tx := a.db.Begin()
70+
tx := db.Begin()
7071
tx.Model(download).Updates(map[string]interface{}{"download_count": gorm.Expr("download_count + 1")})
7172
var subject string
7273
if claims != nil {
@@ -81,12 +82,13 @@ func (a *API) DownloadURL(w http.ResponseWriter, r *http.Request) error {
8182
// DownloadList lists all purchased downloads for an order or a user.
8283
func (a *API) DownloadList(w http.ResponseWriter, r *http.Request) error {
8384
ctx := r.Context()
85+
db := a.DB(r)
8486
orderID := gcontext.GetOrderID(ctx)
8587
log := getLogEntry(r)
8688

8789
order := &models.Order{}
8890
if orderID != "" {
89-
if result := a.db.Where("id = ?", orderID).First(order); result.Error != nil {
91+
if result := db.Where("id = ?", orderID).First(order); result.Error != nil {
9092
if result.RecordNotFound() {
9193
return notFoundError("Download order not found")
9294
}
@@ -106,10 +108,10 @@ func (a *API) DownloadList(w http.ResponseWriter, r *http.Request) error {
106108
}
107109
}
108110

109-
orderTable := a.db.NewScope(models.Order{}).QuotedTableName()
110-
downloadsTable := a.db.NewScope(models.Download{}).QuotedTableName()
111+
orderTable := db.NewScope(models.Order{}).QuotedTableName()
112+
downloadsTable := db.NewScope(models.Download{}).QuotedTableName()
111113

112-
query := a.db.Joins("join " + orderTable + " ON " + downloadsTable + ".order_id = " + orderTable + ".id and " + orderTable + ".payment_state = 'paid'")
114+
query := db.Joins("join " + orderTable + " ON " + downloadsTable + ".order_id = " + orderTable + ".id and " + orderTable + ".payment_state = 'paid'")
113115
if order != nil {
114116
query = query.Where(orderTable+".id = ?", order.ID)
115117
} else {

api/instance.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func (a *API) loadInstance(w http.ResponseWriter, r *http.Request) (context.Cont
1616
instanceID := chi.URLParam(r, "instance_id")
1717
logEntrySetField(r, "instance_id", instanceID)
1818

19-
i, err := models.GetInstance(a.db, instanceID)
19+
i, err := models.GetInstance(a.DB(r), instanceID)
2020
if err != nil {
2121
if models.IsNotFoundError(err) {
2222
return nil, notFoundError("Instance not found")
@@ -47,12 +47,14 @@ type InstanceResponse struct {
4747
}
4848

4949
func (a *API) CreateInstance(w http.ResponseWriter, r *http.Request) error {
50+
db := a.DB(r)
51+
5052
params := InstanceRequestParams{}
5153
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
5254
return badRequestError("Error decoding params: %v", err)
5355
}
5456

55-
_, err := models.GetInstanceByUUID(a.db, params.UUID)
57+
_, err := models.GetInstanceByUUID(db, params.UUID)
5658
if err != nil {
5759
if !models.IsNotFoundError(err) {
5860
return internalServerError("Database error looking up instance").WithInternalError(err)
@@ -66,7 +68,7 @@ func (a *API) CreateInstance(w http.ResponseWriter, r *http.Request) error {
6668
UUID: params.UUID,
6769
BaseConfig: params.BaseConfig,
6870
}
69-
if err = models.CreateInstance(a.db, &i); err != nil {
71+
if err = models.CreateInstance(db, &i); err != nil {
7072
return internalServerError("Database error creating instance").WithInternalError(err)
7173
}
7274

@@ -95,15 +97,15 @@ func (a *API) UpdateInstance(w http.ResponseWriter, r *http.Request) error {
9597
i.BaseConfig = params.BaseConfig
9698
}
9799

98-
if err := models.UpdateInstance(a.db, i); err != nil {
100+
if err := models.UpdateInstance(a.DB(r), i); err != nil {
99101
return internalServerError("Database error updating instance").WithInternalError(err)
100102
}
101103
return sendJSON(w, http.StatusOK, i)
102104
}
103105

104106
func (a *API) DeleteInstance(w http.ResponseWriter, r *http.Request) error {
105107
i := gcontext.GetInstance(r.Context())
106-
if err := models.DeleteInstance(a.db, i); err != nil {
108+
if err := models.DeleteInstance(a.DB(r), i); err != nil {
107109
return internalServerError("Database error deleting instance").WithInternalError(err)
108110
}
109111

api/order.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ func (a *API) withOrderID(w http.ResponseWriter, r *http.Request) (context.Conte
8585
// ClaimOrders will look for any orders with no user id belonging to an email and claim them
8686
func (a *API) ClaimOrders(w http.ResponseWriter, r *http.Request) error {
8787
ctx := r.Context()
88+
db := a.DB(r)
8889
log := getLogEntry(r)
8990
instanceID := gcontext.GetInstanceID(ctx)
9091

@@ -103,7 +104,7 @@ func (a *API) ClaimOrders(w http.ResponseWriter, r *http.Request) error {
103104
})
104105

105106
// now find all the order associated with that email
106-
query := orderQuery(a.db)
107+
query := orderQuery(db)
107108
query = query.Where(&models.Order{
108109
InstanceID: instanceID,
109110
UserID: "",
@@ -115,7 +116,7 @@ func (a *API) ClaimOrders(w http.ResponseWriter, r *http.Request) error {
115116
return internalServerError("Failed to query for orders with email: %s", claims.Email).WithInternalError(res.Error)
116117
}
117118

118-
tx := a.db.Begin()
119+
tx := db.Begin()
119120

120121
// create the user
121122
user := models.User{
@@ -154,7 +155,7 @@ func (a *API) ReceiptView(w http.ResponseWriter, r *http.Request) error {
154155
logEntrySetField(r, "order_id", id)
155156

156157
order := &models.Order{}
157-
if result := orderQuery(a.db).Preload("Transactions").First(order, "id = ?", id); result.Error != nil {
158+
if result := orderQuery(a.DB(r)).Preload("Transactions").First(order, "id = ?", id); result.Error != nil {
158159
if result.RecordNotFound() {
159160
return notFoundError("Order not found")
160161
}
@@ -198,7 +199,7 @@ func (a *API) ResendOrderReceipt(w http.ResponseWriter, r *http.Request) error {
198199
}
199200

200201
order := &models.Order{}
201-
if result := orderQuery(a.db).Preload("Transactions").First(order, "id = ?", id); result.Error != nil {
202+
if result := orderQuery(a.DB(r)).Preload("Transactions").First(order, "id = ?", id); result.Error != nil {
202203
if result.RecordNotFound() {
203204
return notFoundError("Order not found")
204205
}
@@ -246,7 +247,7 @@ func (a *API) OrderList(w http.ResponseWriter, r *http.Request) error {
246247

247248
var err error
248249
params := r.URL.Query()
249-
query := orderQuery(a.db)
250+
query := orderQuery(a.DB(r))
250251
query, err = parseOrderParams(query, params)
251252
if err != nil {
252253
return badRequestError("Bad parameters in query: %v", err)
@@ -286,7 +287,7 @@ func (a *API) OrderView(w http.ResponseWriter, r *http.Request) error {
286287
log := getLogEntry(r)
287288

288289
order := &models.Order{}
289-
if result := orderQuery(a.db).First(order, "id = ?", id); result.Error != nil {
290+
if result := orderQuery(a.DB(r)).First(order, "id = ?", id); result.Error != nil {
290291
if result.RecordNotFound() {
291292
return notFoundError("Order not found")
292293
}
@@ -338,7 +339,7 @@ func (a *API) OrderCreate(w http.ResponseWriter, r *http.Request) error {
338339
"email": params.Email,
339340
"currency": params.Currency,
340341
}).Debug("Created order, starting to process request")
341-
tx := a.db.Begin()
342+
tx := a.DB(r).Begin()
342343

343344
order.IP = r.RemoteAddr
344345
order.MetaData = params.MetaData
@@ -425,6 +426,7 @@ func (a *API) OrderCreate(w http.ResponseWriter, r *http.Request) error {
425426
// There are also blocks to changing certain fields after the state has been locked
426427
func (a *API) OrderUpdate(w http.ResponseWriter, r *http.Request) error {
427428
ctx := r.Context()
429+
db := a.DB(r)
428430
orderID := gcontext.GetOrderID(ctx)
429431
log := getLogEntry(r)
430432
claims := gcontext.GetClaims(ctx)
@@ -440,7 +442,7 @@ func (a *API) OrderUpdate(w http.ResponseWriter, r *http.Request) error {
440442
// verify that the order exists
441443
existingOrder := new(models.Order)
442444

443-
rsp := orderQuery(a.db).First(existingOrder, "id = ?", orderID)
445+
rsp := orderQuery(db).First(existingOrder, "id = ?", orderID)
444446
if rsp.RecordNotFound() {
445447
return notFoundError("Failed to find order with id '%s'", orderID)
446448
}
@@ -486,7 +488,7 @@ func (a *API) OrderUpdate(w http.ResponseWriter, r *http.Request) error {
486488
changes = append(changes, "vatnumber")
487489
}
488490

489-
tx := a.db.Begin()
491+
tx := db.Begin()
490492

491493
//
492494
// handle the addresses

api/payments.go

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func (a *API) PaymentListForUser(w http.ResponseWriter, r *http.Request) error {
4545
return notFoundError("Couldn't find a record for " + userID)
4646
}
4747

48-
trans, httpErr := queryForTransactions(a.db, log, "user_id = ?", userID)
48+
trans, httpErr := queryForTransactions(a.DB(r), log, "user_id = ?", userID)
4949
if httpErr != nil {
5050
return httpErr
5151
}
@@ -60,7 +60,7 @@ func (a *API) PaymentListForOrder(w http.ResponseWriter, r *http.Request) error
6060
orderID := gcontext.GetOrderID(ctx)
6161
claims := gcontext.GetClaims(ctx)
6262

63-
order, httpErr := queryForOrder(a.db, orderID, log)
63+
order, httpErr := queryForOrder(a.DB(r), orderID, log)
6464
if httpErr != nil {
6565
return httpErr
6666
}
@@ -138,7 +138,7 @@ func (a *API) PaymentCreate(w http.ResponseWriter, r *http.Request) error {
138138
}
139139

140140
orderID := gcontext.GetOrderID(ctx)
141-
tx := a.db.Begin()
141+
tx := a.DB(r).Begin()
142142
order := &models.Order{}
143143
loader := tx.
144144
Preload("LineItems").
@@ -237,9 +237,10 @@ func (a *API) PaymentCreate(w http.ResponseWriter, r *http.Request) error {
237237
func (a *API) PaymentConfirm(w http.ResponseWriter, r *http.Request) error {
238238
ctx := r.Context()
239239
log := getLogEntry(r)
240+
db := a.DB(r)
240241

241242
payID := chi.URLParam(r, "payment_id")
242-
trans, httpErr := a.getTransaction(payID)
243+
trans, httpErr := getTransaction(db, payID)
243244
if httpErr != nil {
244245
return httpErr
245246
}
@@ -260,7 +261,7 @@ func (a *API) PaymentConfirm(w http.ResponseWriter, r *http.Request) error {
260261
}
261262

262263
order := &models.Order{}
263-
if rsp := a.db.Find(order, "id = ?", trans.OrderID); rsp.Error != nil {
264+
if rsp := db.Find(order, "id = ?", trans.OrderID); rsp.Error != nil {
264265
if rsp.RecordNotFound() {
265266
return notFoundError("Order not found")
266267
}
@@ -286,7 +287,7 @@ func (a *API) PaymentConfirm(w http.ResponseWriter, r *http.Request) error {
286287
return internalServerError("Error on provider while trying to confirm: %v. Try again later.", err)
287288
}
288289

289-
tx := a.db.Begin()
290+
tx := db.Begin()
290291

291292
if trans.InvoiceNumber == 0 {
292293
invoiceNumber, err := models.NextInvoiceNumber(tx, order.InstanceID)
@@ -311,7 +312,7 @@ func (a *API) PaymentConfirm(w http.ResponseWriter, r *http.Request) error {
311312
func (a *API) PaymentList(w http.ResponseWriter, r *http.Request) error {
312313
log := getLogEntry(r)
313314
instanceID := gcontext.GetInstanceID(r.Context())
314-
query := a.db.Where("instance_id = ?", instanceID)
315+
query := a.DB(r).Where("instance_id = ?", instanceID)
315316

316317
query, err := parsePaymentQueryParams(query, r.URL.Query())
317318
if err != nil {
@@ -328,7 +329,7 @@ func (a *API) PaymentList(w http.ResponseWriter, r *http.Request) error {
328329
// PaymentView returns information about a single payment. It is only available to admins.
329330
func (a *API) PaymentView(w http.ResponseWriter, r *http.Request) error {
330331
payID := chi.URLParam(r, "payment_id")
331-
trans, httpErr := a.getTransaction(payID)
332+
trans, httpErr := getTransaction(a.DB(r), payID)
332333
if httpErr != nil {
333334
return httpErr
334335
}
@@ -339,6 +340,7 @@ func (a *API) PaymentView(w http.ResponseWriter, r *http.Request) error {
339340
// refunds if desired. It is only available to admins.
340341
func (a *API) PaymentRefund(w http.ResponseWriter, r *http.Request) error {
341342
ctx := r.Context()
343+
db := a.DB(r)
342344
config := gcontext.GetConfig(ctx)
343345
params := PaymentParams{Currency: "USD"}
344346
err := json.NewDecoder(r.Body).Decode(&params)
@@ -347,7 +349,7 @@ func (a *API) PaymentRefund(w http.ResponseWriter, r *http.Request) error {
347349
}
348350

349351
payID := chi.URLParam(r, "payment_id")
350-
trans, httpErr := a.getTransaction(payID)
352+
trans, httpErr := getTransaction(db, payID)
351353
if httpErr != nil {
352354
return httpErr
353355
}
@@ -369,7 +371,7 @@ func (a *API) PaymentRefund(w http.ResponseWriter, r *http.Request) error {
369371
}
370372

371373
log := getLogEntry(r)
372-
order, httpErr := queryForOrder(a.db, trans.OrderID, log)
374+
order, httpErr := queryForOrder(db, trans.OrderID, log)
373375
if httpErr != nil {
374376
return httpErr
375377
}
@@ -398,7 +400,7 @@ func (a *API) PaymentRefund(w http.ResponseWriter, r *http.Request) error {
398400
Status: models.PendingState,
399401
}
400402

401-
tx := a.db.Begin()
403+
tx := db.Begin()
402404
tx.Create(m)
403405
provID := provider.Name()
404406
log.Debugf("Starting refund to %s", provID)
@@ -480,8 +482,8 @@ func (a *API) PreauthorizePayment(w http.ResponseWriter, r *http.Request) error
480482
// ------------------------------------------------------------------------------------------------
481483
// Helpers
482484
// ------------------------------------------------------------------------------------------------
483-
func (a *API) getTransaction(payID string) (*models.Transaction, *HTTPError) {
484-
trans, err := models.GetTransaction(a.db, payID)
485+
func getTransaction(db *gorm.DB, payID string) (*models.Transaction, *HTTPError) {
486+
trans, err := models.GetTransaction(db, payID)
485487
if err != nil {
486488
return nil, internalServerError("Error while querying for transactions").WithInternalError(err)
487489
}

0 commit comments

Comments
 (0)