feat: add zap for log

This commit is contained in:
dapeng 2024-06-07 19:22:16 +08:00
parent 4e65a92d65
commit d8f7b0f7a4
31 changed files with 436 additions and 273 deletions

3
.gitignore vendored
View File

@ -3,4 +3,5 @@
test-app
coverage.txt
demo
demo
*.log

View File

@ -9,21 +9,16 @@ import (
func newCemetery() Cemetery {
return &cemetery{
SimpleLogger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
Logger: _defaultLogger,
tombMap: make(map[GonerId]Tomb),
}
}
type cemetery struct {
Flag
SimpleLogger `gone:"gone-logger"`
tombMap map[GonerId]Tomb
tombs []Tomb
}
func (c *cemetery) SetLogger(logger SimpleLogger) SetLoggerError {
c.SimpleLogger = logger
return nil
Logger `gone:"gone-logger"`
tombMap map[GonerId]Tomb
tombs []Tomb
}
func GetGoneDefaultId(goner Goner) GonerId {

View File

@ -211,8 +211,8 @@ func Test_cemetery_revive(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &cemetery{
SimpleLogger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
Logger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
}
for _, tomb := range tt.fields.goneList {
@ -250,8 +250,8 @@ func (p *ZeroPoint) GetIndex() int {
func Test_cemetery_ReplaceBury(t *testing.T) {
t.Run("replace has default value field", func(t *testing.T) {
c := &cemetery{
SimpleLogger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
Logger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
}
c.Bury(c, IdGoneCemetery)
@ -262,13 +262,13 @@ func Test_cemetery_ReplaceBury(t *testing.T) {
c.ReplaceBury(&logger, IdGoneLogger)
assert.Equal(t, c.SimpleLogger, &logger)
assert.Equal(t, c.Logger, &logger)
})
t.Run("replace revived field", func(t *testing.T) {
c := &cemetery{
SimpleLogger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
Logger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
}
const line GonerId = "the-line"
type Line struct {
@ -304,8 +304,8 @@ func Test_cemetery_ReplaceBury(t *testing.T) {
t.Run("replace revived failed", func(t *testing.T) {
c := &cemetery{
SimpleLogger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
Logger: &defaultLogger{},
tombMap: make(map[GonerId]Tomb),
}
const line GonerId = "the-line"
type Line struct {
@ -331,20 +331,6 @@ func Test_cemetery_ReplaceBury(t *testing.T) {
})
}
func Test_cemetery_SetLogger(t *testing.T) {
c := cemetery{}
type TestLogger struct {
defaultLogger
}
logger := &TestLogger{}
err := c.SetLogger(logger)
assert.Nil(t, err)
assert.Equal(t, c.SimpleLogger, logger)
}
type identityGoner struct {
Flag
}

View File

@ -72,6 +72,8 @@ const (
MustHaveGonerId
InjectError
ConfigError
)
func GonerIdIsExistedError(id GonerId) Error {

2
go.mod
View File

@ -65,6 +65,8 @@ require (
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
go.uber.org/mock v0.4.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/arch v0.7.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f // indirect

4
go.sum
View File

@ -464,10 +464,14 @@ go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=

View File

@ -11,9 +11,9 @@ import (
type propertiesConfigure struct {
gone.Flag
gone.SimpleLogger `gone:"gone-logger"`
props *properties.Properties
cemetery gone.Cemetery `gone:"gone-cemetery"`
gone.Logger `gone:"gone-logger"`
props *properties.Properties
cemetery gone.Cemetery `gone:"gone-cemetery"`
}
func (c *propertiesConfigure) Get(key string, v any, defaultVal string) error {
@ -158,7 +158,7 @@ func decodeSlice(sliceElementType reflect.Type, k string, conf PropertiesConfigu
}
func (c *propertiesConfigure) isInTestKit() bool {
return c.cemetery.GetTomById(gone.IdGoneTestKit) != nil
return c.cemetery != nil && c.cemetery.GetTomById(gone.IdGoneTestKit) != nil
}
func (c *propertiesConfigure) mustGetProperties() (*properties.Properties, error) {

View File

@ -2,7 +2,6 @@ package config
import (
"github.com/gone-io/gone"
"github.com/gone-io/gone/goner/logrus"
)
func NewConfig() (gone.Vampire, gone.GonerId, gone.GonerOption) {
@ -14,7 +13,6 @@ func NewConfigure() (gone.Goner, gone.GonerId, gone.GonerOption) {
}
func Priest(cemetery gone.Cemetery) error {
_ = logrus.Priest(cemetery)
cemetery.
BuryOnce(NewConfig()).

View File

@ -246,44 +246,6 @@ func (mr *MockTombMockRecorder) SetId(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetId", reflect.TypeOf((*MockTomb)(nil).SetId), arg0)
}
// MockDefaultLogger is a mock of DefaultLogger interface.
type MockDefaultLogger struct {
goneMock.Flag
ctrl *gomock.Controller
recorder *MockDefaultLoggerMockRecorder
}
// MockDefaultLoggerMockRecorder is the mock recorder for MockDefaultLogger.
type MockDefaultLoggerMockRecorder struct {
mock *MockDefaultLogger
}
// NewMockDefaultLogger creates a new mock instance.
func NewMockDefaultLogger(ctrl *gomock.Controller) *MockDefaultLogger {
mock := &MockDefaultLogger{ctrl: ctrl}
mock.recorder = &MockDefaultLoggerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDefaultLogger) EXPECT() *MockDefaultLoggerMockRecorder {
return m.recorder
}
// SetLogger mocks base method.
func (m *MockDefaultLogger) SetLogger(logger gone.SimpleLogger) gone.SetLoggerError {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetLogger", logger)
ret0, _ := ret[0].(gone.SetLoggerError)
return ret0
}
// SetLogger indicates an expected call of SetLogger.
func (mr *MockDefaultLoggerMockRecorder) SetLogger(logger interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLogger", reflect.TypeOf((*MockDefaultLogger)(nil).SetLogger), logger)
}
// MockCemetery is a mock of Cemetery interface.
type MockCemetery struct {
goneMock.Flag
@ -375,10 +337,10 @@ func (mr *MockCemeteryMockRecorder) GetTomByType(arg0 interface{}) *gomock.Call
}
// InjectFuncParameters mocks base method.
func (m *MockCemetery) InjectFuncParameters(fn any, injectBefore func(reflect.Type, int) any, injectAfter func(reflect.Type, int, *any)) ([]any, error) {
func (m *MockCemetery) InjectFuncParameters(fn any, injectBefore func(reflect.Type, int) any, injectAfter func(reflect.Type, int)) ([]reflect.Value, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "InjectFuncParameters", fn, injectBefore, injectAfter)
ret0, _ := ret[0].([]any)
ret0, _ := ret[0].([]reflect.Value)
ret1, _ := ret[1].(error)
return ret0, ret1
}

View File

@ -246,44 +246,6 @@ func (mr *MockTombMockRecorder) SetId(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetId", reflect.TypeOf((*MockTomb)(nil).SetId), arg0)
}
// MockDefaultLogger is a mock of DefaultLogger interface.
type MockDefaultLogger struct {
goneMock.Flag
ctrl *gomock.Controller
recorder *MockDefaultLoggerMockRecorder
}
// MockDefaultLoggerMockRecorder is the mock recorder for MockDefaultLogger.
type MockDefaultLoggerMockRecorder struct {
mock *MockDefaultLogger
}
// NewMockDefaultLogger creates a new mock instance.
func NewMockDefaultLogger(ctrl *gomock.Controller) *MockDefaultLogger {
mock := &MockDefaultLogger{ctrl: ctrl}
mock.recorder = &MockDefaultLoggerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDefaultLogger) EXPECT() *MockDefaultLoggerMockRecorder {
return m.recorder
}
// SetLogger mocks base method.
func (m *MockDefaultLogger) SetLogger(logger gone.SimpleLogger) gone.SetLoggerError {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetLogger", logger)
ret0, _ := ret[0].(gone.SetLoggerError)
return ret0
}
// SetLogger indicates an expected call of SetLogger.
func (mr *MockDefaultLoggerMockRecorder) SetLogger(logger interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLogger", reflect.TypeOf((*MockDefaultLogger)(nil).SetLogger), logger)
}
// MockCemetery is a mock of Cemetery interface.
type MockCemetery struct {
goneMock.Flag
@ -374,6 +336,21 @@ func (mr *MockCemeteryMockRecorder) GetTomByType(arg0 interface{}) *gomock.Call
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTomByType", reflect.TypeOf((*MockCemetery)(nil).GetTomByType), arg0)
}
// InjectFuncParameters mocks base method.
func (m *MockCemetery) InjectFuncParameters(fn any, injectBefore func(reflect.Type, int) any, injectAfter func(reflect.Type, int)) ([]reflect.Value, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "InjectFuncParameters", fn, injectBefore, injectAfter)
ret0, _ := ret[0].([]reflect.Value)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// InjectFuncParameters indicates an expected call of InjectFuncParameters.
func (mr *MockCemeteryMockRecorder) InjectFuncParameters(fn, injectBefore, injectAfter interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InjectFuncParameters", reflect.TypeOf((*MockCemetery)(nil).InjectFuncParameters), fn, injectBefore, injectAfter)
}
// ReplaceBury mocks base method.
func (m *MockCemetery) ReplaceBury(arg0 gone.Goner, arg1 gone.GonerId) error {
m.ctrl.T.Helper()
@ -429,21 +406,6 @@ func (mr *MockCemeteryMockRecorder) goneFlag() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "goneFlag", reflect.TypeOf((*MockCemetery)(nil).goneFlag))
}
// reviveDependence mocks base method.
func (m *MockCemetery) reviveDependence(tomb gone.Tomb) ([]gone.Tomb, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "reviveDependence", tomb)
ret0, _ := ret[0].([]gone.Tomb)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// reviveDependence indicates an expected call of reviveDependence.
func (mr *MockCemeteryMockRecorder) reviveDependence(tomb interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "reviveDependence", reflect.TypeOf((*MockCemetery)(nil).reviveDependence), tomb)
}
// MockHeaven is a mock of Heaven interface.
type MockHeaven struct {
goneMock.Flag
@ -566,6 +528,18 @@ func (mr *MockHeavenMockRecorder) Install() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Install", reflect.TypeOf((*MockHeaven)(nil).Install))
}
// SetAfterStopSignalWaitSecond mocks base method.
func (m *MockHeaven) SetAfterStopSignalWaitSecond(sec int) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetAfterStopSignalWaitSecond", sec)
}
// SetAfterStopSignalWaitSecond indicates an expected call of SetAfterStopSignalWaitSecond.
func (mr *MockHeavenMockRecorder) SetAfterStopSignalWaitSecond(sec interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAfterStopSignalWaitSecond", reflect.TypeOf((*MockHeaven)(nil).SetAfterStopSignalWaitSecond), sec)
}
// Start mocks base method.
func (m *MockHeaven) Start() gone.Heaven {
m.ctrl.T.Helper()

View File

@ -5,35 +5,3 @@ import "github.com/gone-io/gone"
// Logger log interface
// Deprecated: use gone.Logger instead
type Logger = gone.Logger
//type Logger interface {
// Tracef(format string, args ...any)
// Debugf(format string, args ...any)
// Infof(format string, args ...any)
// Printf(format string, args ...any)
// Warnf(format string, args ...any)
// Warningf(format string, args ...any)
// Errorf(format string, args ...any)
// Fatalf(format string, args ...any)
// Panicf(format string, args ...any)
//
// Trace(args ...any)
// Debug(args ...any)
// Info(args ...any)
// Print(args ...any)
// Warn(args ...any)
// Warning(args ...any)
// Error(args ...any)
// Fatal(args ...any)
// Panic(args ...any)
//
// Traceln(args ...any)
// Debugln(args ...any)
// Infoln(args ...any)
// Println(args ...any)
// Warnln(args ...any)
// Warningln(args ...any)
// Errorln(args ...any)
// Fatalln(args ...any)
// Panicln(args ...any)
//}

View File

@ -57,7 +57,7 @@ func parseLogLevel(level string) logrus.Level {
var l logrus.Level
err := l.UnmarshalText([]byte(level))
if err != nil {
panic("cannot parse logger level")
panic(gone.NewInnerError("cannot parse logger level", gone.ConfigError))
}
return l
}
@ -69,9 +69,9 @@ func parseOutput(output string) io.Writer {
case "stderr":
return os.Stderr
default:
f, err := os.Open(output)
f, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(err)
panic(gone.ToError(err))
}
return f
}

View File

@ -0,0 +1,48 @@
package logrus
import (
"github.com/gone-io/gone"
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func Test_parseOutput(t *testing.T) {
gone.Prepare(Priest).Test(func(log gone.Logger) {
log.Infof("test")
})
}
func Test_parseLogLevel(t *testing.T) {
defer func() {
err := recover()
assert.Error(t, err.(gone.Error))
}()
parseLogLevel("xxx")
}
func Test_parseOutput1(t *testing.T) {
t.Run("create log file failed", func(t *testing.T) {
defer func() {
err := recover()
assert.Error(t, err.(gone.Error))
}()
_ = parseOutput("testdata/noop/test.log")
})
t.Run("create log file success", func(t *testing.T) {
f := parseOutput("testdata/log/test.log")
assert.NotNil(t, f)
defer f.(*os.File).Close()
})
t.Run("stderr", func(t *testing.T) {
f := parseOutput("stderr")
assert.Equal(t, os.Stderr, f)
})
t.Run("stdout", func(t *testing.T) {
f := parseOutput("stdout")
assert.Equal(t, os.Stdout, f)
})
}

View File

@ -2,21 +2,14 @@ package logrus
import (
"github.com/gone-io/gone"
"github.com/gone-io/gone/goner/config"
"github.com/gone-io/gone/goner/tracer"
)
func Priest(cemetery gone.Cemetery) error {
_ = tracer.Priest(cemetery)
if nil == cemetery.GetTomById(gone.IdGoneLogger) {
theLogger, id, option := NewLogger()
cemetery.Bury(theLogger, id, option)
_ = config.Priest(cemetery)
tombs := cemetery.GetTomByType(gone.GetInterfaceType(new(gone.DefaultLogger)))
for _, tomb := range tombs {
goner := tomb.GetGoner()
log := goner.(gone.DefaultLogger)
_ = log.SetLogger(theLogger.(gone.SimpleLogger))
}
}
return nil
theLogger, id, _ := NewLogger()
return cemetery.ReplaceBury(theLogger, id)
}

0
goner/logrus/testdata/log/.keep vendored Normal file
View File

View File

@ -11,6 +11,7 @@ import (
"github.com/gone-io/gone/goner/tracer"
"github.com/gone-io/gone/goner/urllib"
"github.com/gone-io/gone/goner/xorm"
gone_zap "github.com/gone-io/gone/goner/zap"
)
func BasePriest(cemetery gone.Cemetery) error {
@ -20,6 +21,18 @@ func BasePriest(cemetery gone.Cemetery) error {
return nil
}
func ConfigPriest(cemetery gone.Cemetery) error {
return config.Priest(cemetery)
}
func LogrusLoggerPriest(cemetery gone.Cemetery) error {
return logrus.Priest(cemetery)
}
func ZapLoggerPriest(cemetery gone.Cemetery) error {
return gone_zap.Priest(cemetery)
}
func GinPriest(cemetery gone.Cemetery) error {
_ = gin.Priest(cemetery)
return nil

View File

@ -13,7 +13,7 @@ func NewTracer() (gone.Goner, gone.GonerId, gone.GonerOption) {
type tracer struct {
gone.Flag
gone.SimpleLogger `gone:"gone-logger"`
gone.Logger `gone:"gone-logger"`
}
var xMap sync.Map

View File

@ -26,10 +26,7 @@ func TestTracer(t *testing.T) {
}
tracer.SetTraceId(traceId, fn)
}, Priest, func(cemetery gone.Cemetery) error {
cemetery.Bury(gone.NewSimpleLogger())
return nil
})
}, Priest)
}
func BenchmarkTracer_GetTraceId(b *testing.B) {
@ -53,8 +50,5 @@ func BenchmarkTracer_GetTraceId(b *testing.B) {
tracer.SetTraceId(traceId, func() {
fn()
})
}, Priest, func(cemetery gone.Cemetery) error {
cemetery.Bury(gone.NewSimpleLogger())
return nil
})
}, Priest)
}

25
goner/zap/interface.go Normal file
View File

@ -0,0 +1,25 @@
package gone_zap
import (
"github.com/gone-io/gone"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Field = zapcore.Field
type Option = zap.Option
type Logger interface {
Debug(msg string, fields ...Field)
Info(msg string, fields ...Field)
Warn(msg string, fields ...Field)
Error(msg string, fields ...Field)
Panic(msg string, fields ...Field)
Fatal(msg string, fields ...Field)
Named(s string) Logger
WithOptions(opts ...Option) Logger
With(fields ...Field) Logger
Sugar() gone.Logger
sugar() *zap.SugaredLogger
}

113
goner/zap/logger.go Normal file
View File

@ -0,0 +1,113 @@
package gone_zap
import (
"fmt"
"github.com/gone-io/gone"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"reflect"
)
func NewZapLogger() (gone.Goner, gone.GonerId, gone.IsDefault) {
return &log{}, "zap", true
}
type log struct {
gone.Flag
*zap.Logger
level string `gone:"config,log.level,default=info"`
reportCaller bool `gone:"config,log.report-caller,default=true"`
output string `gone:"config,log.output,default=stdout"`
format string `gone:"config,log.format,default=text"`
}
func (l *log) Named(s string) Logger {
if s == "" {
return l
}
return &log{Logger: l.Logger.Named(s)}
}
func (l *log) WithOptions(opts ...Option) Logger {
if len(opts) == 0 {
return l
}
return &log{Logger: l.Logger.WithOptions(opts...)}
}
func (l *log) With(fields ...Field) Logger {
if len(fields) == 0 {
return l
}
return &log{Logger: l.Logger.With(fields...)}
}
func (l *log) Sugar() gone.Logger {
return &sugar{SugaredLogger: l.Logger.Sugar()}
}
func (l *log) sugar() *zap.SugaredLogger {
if l.Logger == nil {
_ = l.AfterRevive()
}
return l.Logger.Sugar()
}
func (l *log) AfterRevive() (err error) {
if l.Logger == nil {
cfg := zap.Config{
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
Development: false,
Encoding: "json",
EncoderConfig: zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "", // 不记录日志调用位置
FunctionKey: zapcore.OmitKey,
MessageKey: "message",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.RFC3339TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
OutputPaths: []string{"stdout", "testdata/test.log"},
ErrorOutputPaths: []string{"testdata/error.log"},
}
l.Logger, err = cfg.Build()
//l.Logger, err = zap.NewProduction()
if err != nil {
return gone.ToError(err)
}
}
return nil
}
func (l *log) Start(gone.Cemetery) error {
return nil
}
func (l *log) Stop(gone.Cemetery) error {
defer l.Logger.Sync()
return nil
}
func (l *log) Suck(conf string, v reflect.Value, field reflect.StructField) error {
t := field.Type
goner := l.Named(conf)
if gone.IsCompatible(t, goner) {
v.Set(reflect.ValueOf(goner))
return nil
}
sLogger := goner.Sugar()
if gone.IsCompatible(t, sLogger) {
v.Set(reflect.ValueOf(sLogger))
return nil
}
return gone.NewInnerError(
fmt.Sprintf("the attribute(%s) do not support type(%s.%s) for gone zap tag; use gone.Logger or gone_zap.Logger instead", field.Name, t.PkgPath(), t.Name()),
gone.NotCompatible,
)
}

15
goner/zap/priest.go Normal file
View File

@ -0,0 +1,15 @@
package gone_zap
import (
"github.com/gone-io/gone"
"github.com/gone-io/gone/goner/config"
)
func Priest(cemetery gone.Cemetery) error {
_ = config.Priest(cemetery)
cemetery.BuryOnce(NewZapLogger())
theLogger, id, _ := NewSugar()
return cemetery.ReplaceBury(theLogger, id)
}

57
goner/zap/sugar.go Normal file
View File

@ -0,0 +1,57 @@
package gone_zap
import (
"github.com/gone-io/gone"
"go.uber.org/zap"
)
func NewSugar() (gone.Goner, gone.GonerId, gone.IsDefault) {
logger, err := zap.NewDevelopment(zap.AddStacktrace(zap.ErrorLevel))
if err != nil {
panic(gone.ToError(err))
}
return &sugar{
SugaredLogger: logger.Sugar(),
}, gone.IdGoneLogger, true
}
type sugar struct {
gone.Flag
*zap.SugaredLogger
logger Logger `gone:"*"`
}
func (l *sugar) AfterRevive() error {
l.SugaredLogger = l.logger.sugar()
return nil
}
func (l *sugar) Tracef(format string, args ...any) {
l.Debugf(format, args...)
}
func (l *sugar) Trace(args ...any) {
l.Debug(args...)
}
func (l *sugar) Traceln(args ...any) {
l.Debugln(args...)
}
func (l *sugar) Printf(format string, args ...any) {
l.Infof(format, args...)
}
func (l *sugar) Print(args ...any) {
l.Info(args...)
}
func (l *sugar) Println(args ...any) {
l.Infoln(args...)
}
func (l *sugar) Warningf(format string, args ...any) {
l.Warnf(format, args...)
}
func (l *sugar) Warning(args ...any) {
l.Warn(args...)
}
func (l *sugar) Warningln(args ...any) {
l.Warnln(args...)
}

12
goner/zap/sugar_test.go Normal file
View File

@ -0,0 +1,12 @@
package gone_zap
import (
"github.com/gone-io/gone"
"testing"
)
func TestNewSugar(t *testing.T) {
gone.Prepare(Priest).Test(func(log gone.Logger) {
log.Info("test")
})
}

0
goner/zap/testdata/.keep vendored Normal file
View File

View File

@ -12,7 +12,7 @@ import (
func New(priests ...Priest) Heaven {
cemetery := newCemetery()
h := heaven{
SimpleLogger: &defaultLogger{},
Logger: _defaultLogger,
cemetery: cemetery,
priests: priests,
signal: make(chan os.Signal),
@ -22,6 +22,7 @@ func New(priests ...Priest) Heaven {
h.
cemetery.
Bury(NewSimpleLogger()).
Bury(&h, IdGoneHeaven, IsDefault(true)).
Bury(cemetery, IdGoneCemetery, IsDefault(true))
return &h
@ -30,8 +31,8 @@ func New(priests ...Priest) Heaven {
type heaven struct {
Flag
SimpleLogger `gone:"gone-logger"`
cemetery Cemetery
Logger `gone:"gone-logger"`
cemetery Cemetery
priests []Priest
@ -55,11 +56,6 @@ func getAngelType() reflect.Type {
return reflect.TypeOf(angelPtr).Elem()
}
func (h *heaven) SetLogger(logger SimpleLogger) SetLoggerError {
h.SimpleLogger = logger
return nil
}
func (h *heaven) GetHeavenStopSignal() <-chan struct{} {
return h.stopSignal
}

View File

@ -7,13 +7,6 @@ import (
"testing"
)
func Test_heaven_SetLogger(t *testing.T) {
h := heaven{}
err := h.SetLogger(&defaultLogger{})
assert.Nil(t, err)
}
func Test_heaven_burial(t *testing.T) {
executed := false
func() {

View File

@ -66,7 +66,7 @@ func WrapNormalFnToProcess(fn any) Process {
}
// IsCompatible t Type can put in goner
func IsCompatible(t reflect.Type, goner Goner) bool {
func IsCompatible(t reflect.Type, goner any) bool {
gonerType := reflect.TypeOf(goner)
switch t.Kind() {

View File

@ -46,11 +46,6 @@ type Tomb interface {
SetDefault(isDefault bool) Tomb
}
type SetLoggerError error
type DefaultLogger interface {
SetLogger(logger SimpleLogger) SetLoggerError
}
// Cemetery which is for burying and reviving Goner
type Cemetery interface {
Goner

View File

@ -1,37 +1,73 @@
package gone
import "fmt"
import (
"log"
)
type SimpleLogger interface {
Tracef(format string, args ...any)
Errorf(format string, args ...any)
Warnf(format string, args ...any)
Infof(format string, args ...any)
}
var _defaultLogger = &defaultLogger{Logger: new(log.Logger)}
func NewSimpleLogger() (Goner, GonerId) {
return &defaultLogger{}, IdGoneLogger
func NewSimpleLogger() (Goner, GonerId, IsDefault) {
return _defaultLogger, IdGoneLogger, true
}
type defaultLogger struct {
Flag
*log.Logger
}
func (*defaultLogger) Tracef(format string, args ...any) {
format = format + "\n"
fmt.Printf(format, args...)
func (l *defaultLogger) Tracef(format string, args ...any) {
log.Printf(format, args...)
}
func (l *defaultLogger) Debugf(format string, args ...any) {
log.Printf(format, args...)
}
func (l *defaultLogger) Infof(format string, args ...any) {
log.Printf(format, args...)
}
func (l *defaultLogger) Warnf(format string, args ...any) {
log.Printf(format, args...)
}
func (l *defaultLogger) Warningf(format string, args ...any) {
log.Printf(format, args...)
}
func (l *defaultLogger) Errorf(format string, args ...any) {
log.Printf(format, args...)
}
func (*defaultLogger) Errorf(format string, args ...any) {
format = format + "\n"
fmt.Printf(format, args...)
func (l *defaultLogger) Trace(args ...any) {
log.Print(args...)
}
func (l *defaultLogger) Debug(args ...any) {
log.Print(args...)
}
func (l *defaultLogger) Info(args ...any) {
log.Print(args...)
}
func (l *defaultLogger) Warn(args ...any) {
log.Print(args...)
}
func (l *defaultLogger) Warning(args ...any) {
log.Print(args...)
}
func (l *defaultLogger) Error(args ...any) {
log.Print(args...)
}
func (*defaultLogger) Warnf(format string, args ...any) {
format = format + "\n"
fmt.Printf(format, args...)
func (l *defaultLogger) Traceln(args ...any) {
log.Println(args...)
}
func (*defaultLogger) Infof(format string, args ...any) {
format = format + "\n"
fmt.Printf(format, args...)
func (l *defaultLogger) Debugln(args ...any) {
log.Println(args...)
}
func (l *defaultLogger) Infoln(args ...any) {
log.Println(args...)
}
func (l *defaultLogger) Warnln(args ...any) {
log.Println(args...)
}
func (l *defaultLogger) Warningln(args ...any) {
log.Println(args...)
}
func (l *defaultLogger) Errorln(args ...any) {
log.Println(args...)
}

View File

@ -6,11 +6,29 @@ import (
)
func Test_defaultLogger_Tracef(t *testing.T) {
logger, id := NewSimpleLogger()
assert.Equal(t, IdGoneLogger, id)
l := logger.(*defaultLogger)
Prepare().Test(func(log Logger) {
logger, _, _ := NewSimpleLogger()
assert.Equal(t, logger, log)
l.Tracef("trace")
l.Errorf("error")
l.Warnf("warn")
log.Tracef("format: %s", "test")
log.Debugf("format: %s", "test")
log.Infof("format: %s", "test")
log.Warnf("format: %s", "test")
log.Warningf("format: %s", "test")
log.Errorf("format: %s", "test")
log.Trace("test")
log.Debug("test")
log.Info("test")
log.Warn("test")
log.Warning("test")
log.Error("test")
log.Traceln("test")
log.Debugln("test")
log.Infoln("test")
log.Warnln("test")
log.Warningln("test")
log.Errorln("test")
})
}

View File

@ -240,43 +240,6 @@ func (mr *MockTombMockRecorder) SetId(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetId", reflect.TypeOf((*MockTomb)(nil).SetId), arg0)
}
// MockDefaultLogger is a mock of DefaultLogger interface.
type MockDefaultLogger struct {
ctrl *gomock.Controller
recorder *MockDefaultLoggerMockRecorder
}
// MockDefaultLoggerMockRecorder is the mock recorder for MockDefaultLogger.
type MockDefaultLoggerMockRecorder struct {
mock *MockDefaultLogger
}
// NewMockDefaultLogger creates a new mock instance.
func NewMockDefaultLogger(ctrl *gomock.Controller) *MockDefaultLogger {
mock := &MockDefaultLogger{ctrl: ctrl}
mock.recorder = &MockDefaultLoggerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDefaultLogger) EXPECT() *MockDefaultLoggerMockRecorder {
return m.recorder
}
// SetLogger mocks base method.
func (m *MockDefaultLogger) SetLogger(logger SimpleLogger) SetLoggerError {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetLogger", logger)
ret0, _ := ret[0].(SetLoggerError)
return ret0
}
// SetLogger indicates an expected call of SetLogger.
func (mr *MockDefaultLoggerMockRecorder) SetLogger(logger interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLogger", reflect.TypeOf((*MockDefaultLogger)(nil).SetLogger), logger)
}
// MockCemetery is a mock of Cemetery interface.
type MockCemetery struct {
ctrl *gomock.Controller