gorm/logger/logger.go

203 lines
5.6 KiB
Go
Raw Normal View History

2020-01-28 18:01:35 +03:00
package logger
2020-01-31 01:35:25 +03:00
import (
2020-05-05 16:28:38 +03:00
"context"
"errors"
2020-10-10 05:56:00 +03:00
"fmt"
"io"
2020-01-31 01:35:25 +03:00
"log"
"os"
2020-02-23 10:07:47 +03:00
"time"
2020-06-02 04:16:07 +03:00
"gorm.io/gorm/utils"
2020-01-31 01:35:25 +03:00
)
// ErrRecordNotFound record not found error
var ErrRecordNotFound = errors.New("record not found")
2020-02-23 10:07:47 +03:00
// Colors
const (
2020-03-14 14:00:41 +03:00
Reset = "\033[0m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
White = "\033[37m"
BlueBold = "\033[34;1m"
2020-03-14 14:00:41 +03:00
MagentaBold = "\033[35;1m"
RedBold = "\033[31;1m"
YellowBold = "\033[33;1m"
2020-02-23 10:07:47 +03:00
)
2020-01-30 10:14:48 +03:00
// LogLevel log level
2020-02-23 10:07:47 +03:00
type LogLevel int
2020-01-31 01:35:25 +03:00
2020-01-30 10:14:48 +03:00
const (
// Silent silent log level
2020-05-30 19:42:52 +03:00
Silent LogLevel = iota + 1
// Error error log level
2020-05-30 19:42:52 +03:00
Error
// Warn warn log level
2020-01-30 10:14:48 +03:00
Warn
// Info info log level
2020-02-23 07:39:26 +03:00
Info
2020-01-30 10:14:48 +03:00
)
2020-02-23 10:07:47 +03:00
// Writer log writer interface
type Writer interface {
Printf(string, ...interface{})
}
// Config logger config
2020-02-23 10:07:47 +03:00
type Config struct {
SlowThreshold time.Duration
Colorful bool
IgnoreRecordNotFoundError bool
LogLevel LogLevel
2020-02-23 10:07:47 +03:00
}
2020-01-28 18:01:35 +03:00
// Interface logger interface
type Interface interface {
2020-01-30 10:14:48 +03:00
LogMode(LogLevel) Interface
2020-05-05 16:28:38 +03:00
Info(context.Context, string, ...interface{})
Warn(context.Context, string, ...interface{})
Error(context.Context, string, ...interface{})
Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)
2020-01-31 01:35:25 +03:00
}
var (
// Discard Discard logger will print any log to io.Discard
Discard = New(log.New(io.Discard, "", log.LstdFlags), Config{})
// Default Default logger
Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), Config{
SlowThreshold: 200 * time.Millisecond,
LogLevel: Warn,
IgnoreRecordNotFoundError: false,
Colorful: true,
})
// Recorder Recorder logger records running SQL into a recorder instance
Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()}
)
2020-02-23 10:07:47 +03:00
// New initialize logger
2020-02-23 10:07:47 +03:00
func New(writer Writer, config Config) Interface {
var (
2020-03-14 14:00:41 +03:00
infoStr = "%s\n[info] "
warnStr = "%s\n[warn] "
errStr = "%s\n[error] "
traceStr = "%s\n[%.3fms] [rows:%v] %s"
2020-10-10 05:56:00 +03:00
traceWarnStr = "%s %s\n[%.3fms] [rows:%v] %s"
traceErrStr = "%s %s\n[%.3fms] [rows:%v] %s"
2020-02-23 10:07:47 +03:00
)
if config.Colorful {
2020-03-14 14:00:41 +03:00
infoStr = Green + "%s\n" + Reset + Green + "[info] " + Reset
warnStr = BlueBold + "%s\n" + Reset + Magenta + "[warn] " + Reset
2020-03-14 14:00:41 +03:00
errStr = Magenta + "%s\n" + Reset + Red + "[error] " + Reset
traceStr = Green + "%s\n" + Reset + Yellow + "[%.3fms] " + BlueBold + "[rows:%v]" + Reset + " %s"
2020-10-10 05:56:00 +03:00
traceWarnStr = Green + "%s " + Yellow + "%s\n" + Reset + RedBold + "[%.3fms] " + Yellow + "[rows:%v]" + Magenta + " %s" + Reset
traceErrStr = RedBold + "%s " + MagentaBold + "%s\n" + Reset + Yellow + "[%.3fms] " + BlueBold + "[rows:%v]" + Reset + " %s"
2020-02-23 10:07:47 +03:00
}
2020-05-29 18:38:03 +03:00
return &logger{
2020-03-14 14:00:41 +03:00
Writer: writer,
Config: config,
infoStr: infoStr,
warnStr: warnStr,
errStr: errStr,
traceStr: traceStr,
traceWarnStr: traceWarnStr,
traceErrStr: traceErrStr,
2020-02-23 10:07:47 +03:00
}
2020-01-31 01:35:25 +03:00
}
2020-02-23 10:07:47 +03:00
type logger struct {
2020-01-31 01:35:25 +03:00
Writer
2020-02-23 10:07:47 +03:00
Config
2020-03-14 14:00:41 +03:00
infoStr, warnStr, errStr string
traceStr, traceErrStr, traceWarnStr string
2020-01-31 01:35:25 +03:00
}
2020-02-23 10:07:47 +03:00
// LogMode log mode
2020-05-29 18:38:03 +03:00
func (l *logger) LogMode(level LogLevel) Interface {
2020-05-31 12:49:31 +03:00
newlogger := *l
newlogger.LogLevel = level
return &newlogger
2020-01-31 01:35:25 +03:00
}
// Info print info
2020-05-05 16:28:38 +03:00
func (l logger) Info(ctx context.Context, msg string, data ...interface{}) {
2020-02-23 10:07:47 +03:00
if l.LogLevel >= Info {
2020-03-14 14:00:41 +03:00
l.Printf(l.infoStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
2020-01-31 01:35:25 +03:00
}
}
// Warn print warn messages
2020-05-05 16:28:38 +03:00
func (l logger) Warn(ctx context.Context, msg string, data ...interface{}) {
2020-02-23 10:07:47 +03:00
if l.LogLevel >= Warn {
2020-03-14 14:00:41 +03:00
l.Printf(l.warnStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
2020-01-31 01:35:25 +03:00
}
}
// Error print error messages
2020-05-05 16:28:38 +03:00
func (l logger) Error(ctx context.Context, msg string, data ...interface{}) {
2020-02-23 10:07:47 +03:00
if l.LogLevel >= Error {
2020-03-14 14:00:41 +03:00
l.Printf(l.errStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
2020-01-31 01:35:25 +03:00
}
2020-01-28 18:01:35 +03:00
}
2020-02-23 07:39:26 +03:00
2020-02-23 10:07:47 +03:00
// Trace print sql message
2020-05-05 16:28:38 +03:00
func (l logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if l.LogLevel <= Silent {
return
}
elapsed := time.Since(begin)
switch {
case err != nil && l.LogLevel >= Error && (!errors.Is(err, ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
sql, rows := fc()
if rows == -1 {
l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= Warn:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
if rows == -1 {
l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
case l.LogLevel == Info:
sql, rows := fc()
if rows == -1 {
l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
2020-02-23 14:41:29 +03:00
}
2020-02-23 07:39:26 +03:00
}
}
type traceRecorder struct {
Interface
BeginAt time.Time
SQL string
RowsAffected int64
Err error
}
// New new trace recorder
func (l traceRecorder) New() *traceRecorder {
return &traceRecorder{Interface: l.Interface, BeginAt: time.Now()}
}
// Trace implement logger interface
func (l *traceRecorder) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
l.BeginAt = begin
l.SQL, l.RowsAffected = fc()
l.Err = err
}