Skip to content

Commit

Permalink
feat: Gorm logger only logs on trace
Browse files Browse the repository at this point in the history
  • Loading branch information
laynax committed Feb 17, 2023
1 parent 1149b59 commit 738ddfd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 25 deletions.
23 changes: 3 additions & 20 deletions pkg/logger/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ package logger

import (
"context"
"errors"
"fmt"
"time"

"github.com/sirupsen/logrus"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

Expand Down Expand Up @@ -53,25 +50,11 @@ func (g gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (strin
},
})

if err == nil {
l.Tracef("%s", gormLoggerMsg)
if err != nil {
l.WithError(err).Tracef(gormLoggerMsg)

return
}

if errors.Is(err, gorm.ErrRecordNotFound) {
l.Tracef(err.Error())

return
}

l.WithError(err).Errorf(gormLoggerMsg)
}

func (g gormLogger) ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{}) {
if g.logger.Level() == logrus.TraceLevel {
return sql, params
}

return sql, nil
l.Tracef(gormLoggerMsg)
}
12 changes: 7 additions & 5 deletions pkg/logger/gorm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ func TestNewGormLogger(t *testing.T) {
},
},
{
name: "Print on error log level with error",
isLogged: true,
name: "Empty on error log level with error",
isLogged: false,
resultError: true,
cfg: Config{
ConsoleEnabled: true,
Expand All @@ -80,8 +80,8 @@ func TestNewGormLogger(t *testing.T) {
},
},
{
name: "Print on debug log level with error",
isLogged: true,
name: "Empty on debug log level with error",
isLogged: false,
resultError: true,
cfg: Config{
ConsoleEnabled: true,
Expand Down Expand Up @@ -129,6 +129,8 @@ func TestNewGormLogger(t *testing.T) {
}

gormDB.Exec(sampleQuery)
println("AAAAAAAA")
println(buffer.String())

if tt.isLogged {
var fields map[string]interface{}
Expand All @@ -146,7 +148,7 @@ func TestNewGormLogger(t *testing.T) {
assert.Contains(t, fields["sql"], "affected_rows")

if tt.resultError {
assert.Equal(t, fields["level"], "error")
assert.Equal(t, fields["level"], "trace")
assert.Contains(t, buffer.String(), "error")
assert.Equal(t, fields["error"], testDBErrorMsg)
} else {
Expand Down

0 comments on commit 738ddfd

Please sign in to comment.