Skip to content

Commit

Permalink
✨ Add log field for sql caller
Browse files Browse the repository at this point in the history
  • Loading branch information
tosone committed Mar 9, 2024
1 parent 45e6bfa commit 82b4a0d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ RESET := $(shell tput -Txterm sgr0)
GOLDFLAGS += -X github.com/go-sigma/sigma/pkg/version.Version=$(shell git describe --tags --dirty --always)
GOLDFLAGS += -X github.com/go-sigma/sigma/pkg/version.BuildDate=$(shell date -u '+%Y-%m-%dT%H:%M:%SZ')
GOLDFLAGS += -X github.com/go-sigma/sigma/pkg/version.GitHash=$(shell git rev-parse --short HEAD)
GOFLAGS = -ldflags '-s -w $(GOLDFLAGS)'
GOFLAGS = -ldflags '-s -w $(GOLDFLAGS)' -trimpath

GOOS ?= linux
GOARCH ?= amd64
Expand Down
33 changes: 33 additions & 0 deletions pkg/logger/glog.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,15 @@ package logger
import (
"context"
"fmt"
"runtime"
"strings"
"time"

"github.com/rs/zerolog"
"gorm.io/gorm/logger"

"github.com/go-sigma/sigma/pkg/configs"
"github.com/go-sigma/sigma/pkg/types/enums"
)

// ZLogger is the logger for gorm
Expand Down Expand Up @@ -53,6 +58,34 @@ func (l ZLogger) Trace(ctx context.Context, begin time.Time, f func() (string, i

event = event.Str("elapsed", time.Since(begin).String())

logLevel := configs.GetConfiguration().Log.Level
if logLevel == enums.LogLevelDebug || logLevel == enums.LogLevelTrace {
for i := 0; i < 15; i++ {
_, f, n, ok := runtime.Caller(i)
if !ok {
break

Check warning on line 66 in pkg/logger/glog.go

View check run for this annotation

Codecov / codecov/patch

pkg/logger/glog.go#L63-L66

Added lines #L63 - L66 were not covered by tests
}
if ok {
if strings.HasPrefix(f, "github.com/go-sigma/sigma/pkg") {
if strings.HasPrefix(f, "github.com/go-sigma/sigma/pkg/dal/query") ||
strings.HasPrefix(f, "github.com/go-sigma/sigma/pkg/dal/dao") ||
strings.HasPrefix(f, "github.com/go-sigma/sigma/pkg/logger") {
continue

Check warning on line 73 in pkg/logger/glog.go

View check run for this annotation

Codecov / codecov/patch

pkg/logger/glog.go#L68-L73

Added lines #L68 - L73 were not covered by tests
}
lastIndex := strings.LastIndex(f, "/")
left := f[:lastIndex]
f = f[lastIndex+1:]
if strings.Contains(left, "/") {
lastIndex = strings.LastIndex(left, "/")
f = left[lastIndex+1:] + "/" + f
}
event.Str("call", fmt.Sprintf("%s:%d", f, n))
break

Check warning on line 83 in pkg/logger/glog.go

View check run for this annotation

Codecov / codecov/patch

pkg/logger/glog.go#L75-L83

Added lines #L75 - L83 were not covered by tests
}
}
}
}

sql, rows := f()
if sql != "" {
event = event.Str("sql", sql)
Expand Down

0 comments on commit 82b4a0d

Please sign in to comment.