logger.go 4.6 KB
Newer Older
1
package internal
m0_50812349's avatar
m0_50812349 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

import (
	"context"
	"fmt"
	"gin-vue-admin/global"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/utils"
	"io/ioutil"
	"log"
	"os"
	"time"
)

15 16 17 18 19 20
type config struct {
	SlowThreshold time.Duration
	Colorful      bool
	LogLevel      logger.LogLevel
}

m0_50812349's avatar
m0_50812349 已提交
21
var (
22 23
	Discard = New(log.New(ioutil.Discard, "", log.LstdFlags), config{})
	Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), config{
m0_50812349's avatar
m0_50812349 已提交
24 25 26 27 28 29 30
		SlowThreshold: 200 * time.Millisecond,
		LogLevel:      logger.Warn,
		Colorful:      true,
	})
	Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()}
)

31
func New(writer logger.Writer, config config) logger.Interface {
m0_50812349's avatar
m0_50812349 已提交
32 33 34 35
	var (
		infoStr      = "%s\n[info] "
		warnStr      = "%s\n[warn] "
		errStr       = "%s\n[error] "
36 37 38
		traceStr     = "%s\n[%.3fms] [rows:%v] %s\n"
		traceWarnStr = "%s %s\n[%.3fms] [rows:%v] %s\n"
		traceErrStr  = "%s %s\n[%.3fms] [rows:%v] %s\n"
m0_50812349's avatar
m0_50812349 已提交
39 40 41 42 43 44
	)

	if config.Colorful {
		infoStr = logger.Green + "%s\n" + logger.Reset + logger.Green + "[info] " + logger.Reset
		warnStr = logger.BlueBold + "%s\n" + logger.Reset + logger.Magenta + "[warn] " + logger.Reset
		errStr = logger.Magenta + "%s\n" + logger.Reset + logger.Red + "[error] " + logger.Reset
45 46 47
		traceStr = logger.Green + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s\n"
		traceWarnStr = logger.Green + "%s " + logger.Yellow + "%s\n" + logger.Reset + logger.RedBold + "[%.3fms] " + logger.Yellow + "[rows:%v]" + logger.Magenta + " %s\n" + logger.Reset
		traceErrStr = logger.RedBold + "%s " + logger.MagentaBold + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s\n"
m0_50812349's avatar
m0_50812349 已提交
48 49
	}

50 51
	return &_logger{
		Writer:       writer,
52
		config:       config,
m0_50812349's avatar
m0_50812349 已提交
53 54 55 56 57 58 59 60 61
		infoStr:      infoStr,
		warnStr:      warnStr,
		errStr:       errStr,
		traceStr:     traceStr,
		traceWarnStr: traceWarnStr,
		traceErrStr:  traceErrStr,
	}
}

62
type _logger struct {
63
	config
64
	logger.Writer
m0_50812349's avatar
m0_50812349 已提交
65 66 67 68
	infoStr, warnStr, errStr            string
	traceStr, traceErrStr, traceWarnStr string
}

69
// LogMode log mode
70
func (c *_logger) LogMode(level logger.LogLevel) logger.Interface {
71
	newLogger := *c
m0_50812349's avatar
m0_50812349 已提交
72 73 74 75
	newLogger.LogLevel = level
	return &newLogger
}

76
// Info print info
77
func (c *_logger) Info(ctx context.Context, message string, data ...interface{}) {
78 79
	if c.LogLevel >= logger.Info {
		c.Printf(c.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
m0_50812349's avatar
m0_50812349 已提交
80 81 82
	}
}

83
// Warn print warn messages
84
func (c *_logger) Warn(ctx context.Context, message string, data ...interface{}) {
85 86
	if c.LogLevel >= logger.Warn {
		c.Printf(c.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
m0_50812349's avatar
m0_50812349 已提交
87 88 89
	}
}

90
// Error print error messages
91
func (c *_logger) Error(ctx context.Context, message string, data ...interface{}) {
92 93
	if c.LogLevel >= logger.Error {
		c.Printf(c.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
m0_50812349's avatar
m0_50812349 已提交
94 95 96
	}
}

97
// Trace print sql message
98
func (c *_logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
99
	if c.LogLevel > 0 {
m0_50812349's avatar
m0_50812349 已提交
100 101
		elapsed := time.Since(begin)
		switch {
102
		case err != nil && c.LogLevel >= logger.Error:
m0_50812349's avatar
m0_50812349 已提交
103 104
			sql, rows := fc()
			if rows == -1 {
105
				c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
m0_50812349's avatar
m0_50812349 已提交
106
			} else {
107
				c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
m0_50812349's avatar
m0_50812349 已提交
108
			}
109
		case elapsed > c.SlowThreshold && c.SlowThreshold != 0 && c.LogLevel >= logger.Warn:
m0_50812349's avatar
m0_50812349 已提交
110
			sql, rows := fc()
111
			slowLog := fmt.Sprintf("SLOW SQL >= %v", c.SlowThreshold)
m0_50812349's avatar
m0_50812349 已提交
112
			if rows == -1 {
113
				c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
m0_50812349's avatar
m0_50812349 已提交
114
			} else {
115
				c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
m0_50812349's avatar
m0_50812349 已提交
116
			}
117
		case c.LogLevel >= logger.Info:
m0_50812349's avatar
m0_50812349 已提交
118 119
			sql, rows := fc()
			if rows == -1 {
120
				c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
m0_50812349's avatar
m0_50812349 已提交
121
			} else {
122
				c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
m0_50812349's avatar
m0_50812349 已提交
123 124 125 126 127
			}
		}
	}
}

128 129 130 131 132
func (c *_logger) Printf(message string, data ...interface{}) {
	if global.GVA_CONFIG.Mysql.LogZap {
		global.GVA_LOG.Info(fmt.Sprintf(message, data...))
	} else {
		c.Writer.Printf(message, data...)
m0_50812349's avatar
m0_50812349 已提交
133
	}
m0_50812349's avatar
m0_50812349 已提交
134
}
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

type traceRecorder struct {
	logger.Interface
	BeginAt      time.Time
	SQL          string
	RowsAffected int64
	Err          error
}

func (t traceRecorder) New() *traceRecorder {
	return &traceRecorder{Interface: t.Interface, BeginAt: time.Now()}
}

func (t *traceRecorder) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	t.BeginAt = begin
	t.SQL, t.RowsAffected = fc()
	t.Err = err
}