设置日志打印

This commit is contained in:
Yun
2024-06-21 00:20:54 +08:00
parent daf95bb905
commit 571b852c1a
2 changed files with 33 additions and 7 deletions
+5 -6
View File
@@ -3,7 +3,6 @@ package lockx
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"time" "time"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
@@ -43,8 +42,7 @@ func (g *globalLock) Lock() bool {
resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value, 5).Result() resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value, 5).Result()
if resp != "OK" { if resp != "OK" {
_ = err opt.logger.Errorf(g.ctx, "global lock err resp:%+v err:%+v uniKey:%+v value:%+v", resp, err, g.uniqueKey, g.value)
log.Println("global Lock Lock", resp, err, g.uniqueKey, g.value)
} }
if resp == "OK" { if resp == "OK" {
g.refresh() g.refresh()
@@ -79,7 +77,7 @@ func (g *globalLock) Unlock() bool {
resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value).Result() resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value).Result()
if resp != "OK" { if resp != "OK" {
log.Println("global Lock Unlock", resp, err, g.uniqueKey, g.value) opt.logger.Errorf(g.ctx, "global Unlock err resp:%+v err:%+v uniKey:%+v value:%+v", resp, err, g.uniqueKey, g.value)
} }
g.cancel() g.cancel()
return true return true
@@ -114,7 +112,8 @@ func (g *globalLock) refreshExec() bool {
resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value, 5).Result() resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value, 5).Result()
if resp != "OK" { if resp != "OK" {
log.Println("global Lock refresh", resp, err, g.uniqueKey, g.value) opt.logger.Errorf(g.ctx, "global refresh err resp:%+v err:%+v uniKey:%+v value:%+v", resp, err, g.uniqueKey, g.value)
return false
} }
return resp == "OK" return true
} }
+28 -1
View File
@@ -1,14 +1,20 @@
package lockx package lockx
import "time" import (
"context"
"log"
"time"
)
type option struct { type option struct {
lockTimeout time.Duration // 锁的超时时间 lockTimeout time.Duration // 锁的超时时间
logger Logger // 日志
} }
func defaultOption() *option { func defaultOption() *option {
return &option{ return &option{
lockTimeout: time.Minute * 60, lockTimeout: time.Minute * 60,
logger: &print{},
} }
} }
@@ -32,3 +38,24 @@ func SetTimeout(t time.Duration) Option {
o.lockTimeout = t o.lockTimeout = t
} }
} }
func SetLogger(logger Logger) Option {
return func(o *option) {
o.logger = logger
}
}
type Logger interface {
Errorf(ctx context.Context, format string, v ...any)
Printf(ctx context.Context, format string, v ...any)
}
type print struct{}
func (*print) Errorf(ctx context.Context, format string, v ...any) {
log.Printf(format, v...)
}
func (*print) Printf(ctx context.Context, format string, v ...any) {
log.Printf(format, v...)
}