From 0def23b2b5b5d5ef943ef3fb942b690fb9831263 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Fri, 10 Sep 2021 21:46:32 +0200 Subject: [PATCH] bun trace logging hooks --- internal/db/bundb/bundb.go | 5 ++++ internal/db/bundb/trace.go | 50 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 internal/db/bundb/trace.go diff --git a/internal/db/bundb/bundb.go b/internal/db/bundb/bundb.go index 7ddcab5c7..600de9a59 100644 --- a/internal/db/bundb/bundb.go +++ b/internal/db/bundb/bundb.go @@ -147,6 +147,11 @@ func NewBunDBService(ctx context.Context, c *config.Config, log *logrus.Logger) return nil, fmt.Errorf("database type %s not supported for bundb", strings.ToLower(c.DBConfig.Type)) } + if log.Level >= logrus.TraceLevel { + // add a hook to just log queries and the time they take + conn.DB.AddQueryHook(&debugQueryHook{log: log}) + } + // actually *begin* the connection so that we can tell if the db is there and listening if err := conn.Ping(); err != nil { return nil, fmt.Errorf("db connection error: %s", err) diff --git a/internal/db/bundb/trace.go b/internal/db/bundb/trace.go new file mode 100644 index 000000000..3c0df4442 --- /dev/null +++ b/internal/db/bundb/trace.go @@ -0,0 +1,50 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package bundb + +import ( + "context" + "time" + + "github.com/sirupsen/logrus" + "github.com/uptrace/bun" +) + +// queryHook is just a wrapper for bun.QueryHook +type queryHook bun.QueryHook + +// debugQueryHook implements queryHook +type debugQueryHook struct { + log *logrus.Logger +} + +func (q *debugQueryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context { + // do nothing + return ctx +} + +// AfterQuery logs the time taken to query, the operation (select, update, etc), and the query itself as translated by bun. +func (q *debugQueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) { + dur := time.Now().Sub(event.StartTime).Round(time.Microsecond) + l := q.log.WithFields(logrus.Fields{ + "queryTime": dur, + "operation": event.Operation(), + }) + l.Trace(event.Query) +}