mirror of
https://gitee.ltd/lxh/logger.git
synced 2025-10-23 14:56:16 +08:00
Compare commits
5 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
40a3dc9339 | ||
|
ebae5c29cd | ||
|
4e2f8f6466 | ||
|
40840390ae | ||
|
27dd190fbd |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,5 +1,4 @@
|
|||||||
.idea
|
.idea
|
||||||
vendor
|
vendor
|
||||||
logs
|
logs
|
||||||
cache
|
cache
|
||||||
log
|
|
18
gorm.go
18
gorm.go
@@ -4,10 +4,13 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"go.uber.org/zap"
|
||||||
gl "gorm.io/gorm/logger"
|
gl "gorm.io/gorm/logger"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var gormZap *zap.SugaredLogger
|
||||||
|
|
||||||
// 基于Gorm的日志实现
|
// 基于Gorm的日志实现
|
||||||
type gormLogger struct {
|
type gormLogger struct {
|
||||||
gl.Config
|
gl.Config
|
||||||
@@ -25,7 +28,7 @@ func (l gormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
|
|||||||
if l.LogLevel >= gl.Info {
|
if l.LogLevel >= gl.Info {
|
||||||
// // 去掉第一行
|
// // 去掉第一行
|
||||||
// msg = strings.Join(strings.Split(msg, "\n")[1:], " ")
|
// msg = strings.Join(strings.Split(msg, "\n")[1:], " ")
|
||||||
// Say.Info(msg)
|
// gormZap.Info(msg)
|
||||||
//
|
//
|
||||||
// l.Printf(msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
|
// l.Printf(msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
|
||||||
}
|
}
|
||||||
@@ -60,12 +63,12 @@ func (l gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (strin
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
case err != nil && l.LogLevel >= gl.Error && (!errors.Is(err, gl.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
|
case err != nil && l.LogLevel >= gl.Error && (!errors.Is(err, gl.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
|
||||||
Say.Errorf("%s -> %s", err.Error(), sql)
|
gormZap.Errorf("%s -> %s", err.Error(), sql)
|
||||||
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gl.Warn:
|
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gl.Warn:
|
||||||
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
|
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
|
||||||
Say.Warnf("%v -> %v", slowLog, sql)
|
gormZap.Warnf("%v -> %v", slowLog, sql)
|
||||||
case l.LogLevel == gl.Info:
|
case l.LogLevel == gl.Info:
|
||||||
Say.Info(msg)
|
gormZap.Info(msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,10 +79,15 @@ func NewGormLoggerWithConfig(config gl.Config) gl.Interface {
|
|||||||
|
|
||||||
// DefaultGormLogger 默认的日志实现
|
// DefaultGormLogger 默认的日志实现
|
||||||
func DefaultGormLogger() gl.Interface {
|
func DefaultGormLogger() gl.Interface {
|
||||||
|
// 默认日志级别为Info,如果是生产环境,就是Error
|
||||||
|
logLevel := gl.Info
|
||||||
|
if config.Mode == Prod {
|
||||||
|
logLevel = gl.Error
|
||||||
|
}
|
||||||
return &gormLogger{gl.Config{
|
return &gormLogger{gl.Config{
|
||||||
SlowThreshold: time.Second, // Slow SQL threshold
|
SlowThreshold: time.Second, // Slow SQL threshold
|
||||||
IgnoreRecordNotFoundError: false, // 忽略没找到结果的错误
|
IgnoreRecordNotFoundError: false, // 忽略没找到结果的错误
|
||||||
LogLevel: gl.Info, // Log level
|
LogLevel: logLevel, // Log level
|
||||||
Colorful: false, // Disable color
|
Colorful: false, // Disable color
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
25
gorm_test.go
25
gorm_test.go
@@ -1,9 +1,12 @@
|
|||||||
package logger
|
package logger
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"gitee.ltd/lxh/logger/log"
|
||||||
"gorm.io/driver/mysql"
|
"gorm.io/driver/mysql"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
gl "gorm.io/gorm/logger"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGormLogger(t *testing.T) {
|
func TestGormLogger(t *testing.T) {
|
||||||
@@ -11,7 +14,27 @@ func TestGormLogger(t *testing.T) {
|
|||||||
|
|
||||||
engine, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: DefaultGormLogger()})
|
engine, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: DefaultGormLogger()})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Say.Panicf("mysql connect error: %s", err.Error())
|
log.Panicf("mysql connect error: %s", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
if err := engine.Table("t_tenant").Count(&count).Error; err != nil {
|
||||||
|
t.Log(err)
|
||||||
|
}
|
||||||
|
t.Logf("count: %d", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGormLoggerWithConfig(t *testing.T) {
|
||||||
|
dsn := "saas:saas123@tcp(10.11.0.10:3307)/saas_tenant?charset=utf8mb4&parseTime=True&loc=Local"
|
||||||
|
|
||||||
|
engine, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: NewGormLoggerWithConfig(gl.Config{
|
||||||
|
SlowThreshold: time.Second, // Slow SQL threshold
|
||||||
|
IgnoreRecordNotFoundError: false, // 忽略没找到结果的错误
|
||||||
|
LogLevel: gl.Warn, // Log level
|
||||||
|
Colorful: false, // Disable color
|
||||||
|
})})
|
||||||
|
if err != nil {
|
||||||
|
log.Panicf("mysql connect error: %s", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
var count int64
|
var count int64
|
||||||
|
75
log/say.go
Normal file
75
log/say.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
package log
|
||||||
|
|
||||||
|
import "go.uber.org/zap"
|
||||||
|
|
||||||
|
// Debug uses fmt.Sprint to construct and log a message.
|
||||||
|
func Debug(args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Debug(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info uses fmt.Sprint to construct and log a message.
|
||||||
|
func Info(args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Info(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warn uses fmt.Sprint to construct and log a message.
|
||||||
|
func Warn(args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Warn(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error uses fmt.Sprint to construct and log a message.
|
||||||
|
func Error(args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Error(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Panic uses fmt.Sprint to construct and log a message, then panics.
|
||||||
|
func Panic(args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Panic(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit.
|
||||||
|
func Fatal(args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Fatal(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugf uses fmt.Sprintf to log a templated message.
|
||||||
|
func Debugf(template string, args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Debugf(template, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Infof uses fmt.Sprintf to log a templated message.
|
||||||
|
func Infof(template string, args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Infof(template, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warnf uses fmt.Sprintf to log a templated message.
|
||||||
|
func Warnf(template string, args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Warnf(template, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errorf uses fmt.Sprintf to log a templated message.
|
||||||
|
func Errorf(template string, args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Errorf(template, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Panicf uses fmt.Sprintf to log a templated message, then panics.
|
||||||
|
func Panicf(template string, args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Panicf(template, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.
|
||||||
|
func Fatalf(template string, args ...interface{}) {
|
||||||
|
defer zap.S().Sync()
|
||||||
|
zap.S().Fatalf(template, args...)
|
||||||
|
}
|
10
logger.go
10
logger.go
@@ -8,11 +8,11 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var config LogConfig
|
var config LogConfig
|
||||||
var Say *zap.SugaredLogger
|
var initialized bool
|
||||||
|
|
||||||
// 避免异常,在第一次调用时初始化一个只打印到控制台的logger
|
// 避免异常,在第一次调用时初始化一个只打印到控制台的logger
|
||||||
func init() {
|
func init() {
|
||||||
if Say == nil {
|
if !initialized {
|
||||||
// 从环境变量读取配置
|
// 从环境变量读取配置
|
||||||
var c LogConfig
|
var c LogConfig
|
||||||
if err := env.Parse(&c); err != nil {
|
if err := env.Parse(&c); err != nil {
|
||||||
@@ -47,7 +47,9 @@ func InitLogger(c LogConfig) {
|
|||||||
|
|
||||||
// 增加 caller 信息
|
// 增加 caller 信息
|
||||||
// AddCallerSkip 输出的文件名和行号是调用封装函数的位置,而不是调用日志函数的位置
|
// AddCallerSkip 输出的文件名和行号是调用封装函数的位置,而不是调用日志函数的位置
|
||||||
logger := zap.New(zapcore.NewTee(cores...), zap.AddCaller())
|
logger := zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(1))
|
||||||
Say = logger.Sugar()
|
initialized = true
|
||||||
|
// 给GORM单独生成一个
|
||||||
|
gormZap = zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(3)).Sugar()
|
||||||
zap.ReplaceGlobals(logger)
|
zap.ReplaceGlobals(logger)
|
||||||
}
|
}
|
||||||
|
@@ -1,23 +1,23 @@
|
|||||||
package logger
|
package logger
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"go.uber.org/zap"
|
"gitee.ltd/lxh/logger/log"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestLogger(t *testing.T) {
|
func TestLogger(t *testing.T) {
|
||||||
InitLogger(LogConfig{Mode: Dev, LokiEnable: false, FileEnable: true})
|
InitLogger(LogConfig{Mode: Dev, LokiEnable: false, FileEnable: true})
|
||||||
Say.Debug("芜湖")
|
log.Debug("芜湖")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLogger1(t *testing.T) {
|
func TestLogger1(t *testing.T) {
|
||||||
Say.Info("我是测试消息")
|
log.Info("我是测试消息")
|
||||||
time.Sleep(5 * time.Second)
|
time.Sleep(5 * time.Second)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLogger2(t *testing.T) {
|
func TestLogger2(t *testing.T) {
|
||||||
InitLogger(LogConfig{Mode: Dev, LokiEnable: false, FileEnable: true})
|
InitLogger(LogConfig{Mode: Dev, LokiEnable: false, FileEnable: true})
|
||||||
zap.S().Info("我是测试消息")
|
log.Info("我是测试消息")
|
||||||
time.Sleep(5 * time.Second)
|
//time.Sleep(5 * time.Second)
|
||||||
}
|
}
|
||||||
|
@@ -5,17 +5,20 @@
|
|||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import "gitee.ltd/lxh/logger"
|
import (
|
||||||
|
"gitee.ltd/lxh/logger"
|
||||||
|
"gitee.ltd/lxh/logger/log"
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
logger.InitLogger(logger.LogConfig{Mode: logger.Dev, LokiEnable: false, FileEnable: true})
|
logger.InitLogger(logger.LogConfig{Mode: logger.Dev, LokiEnable: false, FileEnable: true})
|
||||||
logger.Say.Debug("芜湖")
|
log.Debug("芜湖")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 环境变量
|
### 环境变量
|
||||||
```shell
|
```shell
|
||||||
export LOG_MODE=0 # 0: dev, 1: prod
|
export LOG_MODE=0 # development | production
|
||||||
export LOG_LOKI_ENABLE=1 # 是否启用Loki 0: disable, 1: enable
|
export LOG_LOKI_ENABLE=1 # 是否启用Loki 0: disable, 1: enable
|
||||||
export LOG_FILE_ENABLE=0 # 是否启用输出到文件 0: disable, 1: enable
|
export LOG_FILE_ENABLE=0 # 是否启用输出到文件 0: disable, 1: enable
|
||||||
export LOG_LOKI_HOST=10.0.0.31 # Loki地址
|
export LOG_LOKI_HOST=10.0.0.31 # Loki地址
|
||||||
|
Reference in New Issue
Block a user