Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created August 16, 2022 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonmga/269aec52bc1484e2a46760cd6ef678ba to your computer and use it in GitHub Desktop.
Save alfonmga/269aec52bc1484e2a46760cd6ef678ba to your computer and use it in GitHub Desktop.
Gorm -> Logrus
package gormlogrus
import (
"context"
"errors"
"time"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"gorm.io/gorm/utils"
)
type logger struct {
log *logrus.Entry
SlowThreshold time.Duration
SourceField string
SkipErrRecordNotFound bool
LogLevel gormlogger.LogLevel
}
func New(l *logrus.Entry) *logger {
return &logger{
log: l,
SkipErrRecordNotFound: true,
}
}
func (l *logger) LogMode(level gormlogger.LogLevel) gormlogger.Interface {
l.LogLevel = level
return l
}
func (l *logger) Info(ctx context.Context, s string, args ...interface{}) {
if l.LogLevel >= gormlogger.Info {
l.log.WithContext(ctx).Infof(s, args)
}
}
func (l *logger) Warn(ctx context.Context, s string, args ...interface{}) {
if l.LogLevel >= gormlogger.Info {
l.log.WithContext(ctx).Warnf(s, args)
}
}
func (l *logger) Error(ctx context.Context, s string, args ...interface{}) {
if l.LogLevel >= gormlogger.Error {
l.log.WithContext(ctx).Errorf(s, args)
}
}
func (l *logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if l.LogLevel <= gormlogger.Silent {
return
}
elapsed := time.Since(begin)
sql, _ := fc()
fields := logrus.Fields{}
if l.SourceField != "" {
fields[l.SourceField] = utils.FileWithLineNum()
}
if err != nil && !(errors.Is(err, gorm.ErrRecordNotFound) && l.SkipErrRecordNotFound) {
fields[logrus.ErrorKey] = err
l.log.WithContext(ctx).WithFields(fields).Errorf("%s [%s]", sql, elapsed)
return
}
if l.SlowThreshold != 0 && elapsed > l.SlowThreshold {
l.log.WithContext(ctx).WithFields(fields).Warnf("%s [%s]", sql, elapsed)
return
}
l.log.WithContext(ctx).WithFields(fields).Debugf("%s [%s]", sql, elapsed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment