From 45580219c9b0f0636f0724d120bcc95333472458 Mon Sep 17 00:00:00 2001 From: limpo1989 Date: Fri, 10 Nov 2023 17:07:52 +0800 Subject: [PATCH] Redesign the AppEvent interface to get away from Go-Spring dependence --- README.md | 8 ++++---- README_CN.md | 8 ++++---- gs/app.go | 34 +++++++++------------------------- gs/gs.go | 8 ++++---- gs/gs_bean.go | 4 ++-- gs/logger.go | 24 +++++++++++++++++++++--- internal/log/logger.go | 21 +++++---------------- internal/utils/type.go | 14 ++++++++++++++ internal/utils/type_test.go | 8 ++++++++ 9 files changed, 71 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 607b16fe..9b3905b2 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ func main() { } // Output: -// time=2023-09-25T14:50:32.927+08:00 level=INFO source=main.go:14 msg="Hello world" logger=go-spring type=main.MyApp +// time=2023-09-25T14:50:32.927+08:00 level=INFO source=main.go:14 msg="Hello world" logger=go-spring ``` #### Bean register @@ -483,9 +483,9 @@ func main() { } // Output: -// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello primary logger","logger":"app","type":"main.App"} -// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello system logger","logger":"sys","type":"main.App"} -// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello trace logger","logger":"trace","type":"main.App"} +// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello primary logger","logger":"app"} +// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello system logger","logger":"sys"} +// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello trace logger","logger":"trace"} ``` ### Dependent order event diff --git a/README_CN.md b/README_CN.md index 2cc719af..49075113 100644 --- a/README_CN.md +++ b/README_CN.md @@ -90,7 +90,7 @@ func main() { } // Output: -// time=2023-09-25T14:50:32.927+08:00 level=INFO source=main.go:14 msg="Hello world" logger=go-spring type=main.MyApp +// time=2023-09-25T14:50:32.927+08:00 level=INFO source=main.go:14 msg="Hello world" logger=go-spring ``` #### Bean register @@ -482,9 +482,9 @@ func main() { } // Output: -// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello primary logger","logger":"app","type":"main.App"} -// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello system logger","logger":"sys","type":"main.App"} -// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello trace logger","logger":"trace","type":"main.App"} +// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello primary logger","logger":"app"} +// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello system logger","logger":"sys"} +// {"time":"2023-10-27T12:10:14.8040121+08:00","level":"INFO","msg":"hello trace logger","logger":"trace"} ``` ### 依赖序事件 diff --git a/gs/app.go b/gs/app.go index 801b112c..d5ee9450 100644 --- a/gs/app.go +++ b/gs/app.go @@ -29,17 +29,11 @@ import ( "github.com/go-spring-projects/go-spring/conf" "github.com/go-spring-projects/go-spring/gs/arg" - "github.com/go-spring-projects/go-spring/internal/utils" ) -// AppRunner . -type AppRunner interface { - Run(ctx Context) -} - // AppEvent start and stop events type AppEvent interface { - OnAppStart(ctx Context) + OnAppStart(ctx context.Context) OnAppStop(ctx context.Context) } @@ -87,9 +81,7 @@ func (app *App) run(resourceLocator ResourceLocator) error { return err } - var logger = GetLogger("", utils.TypeName(app)) - - app.onAppRun(app.container) + var logger = GetLogger() app.onAppStart(app.container) @@ -105,7 +97,7 @@ func (app *App) run(resourceLocator ResourceLocator) error { <-app.exitChan - app.onAppStop(context.Background()) + app.onAppStop(app.container) app.container.Close() @@ -114,32 +106,24 @@ func (app *App) run(resourceLocator ResourceLocator) error { return nil } -func (app *App) onAppRun(ctx Context) { - for _, bean := range app.container.Dependencies(true) { - x := bean.Value().Interface() - - if ar, ok := x.(AppRunner); ok { - ar.Run(ctx) - } - } -} - func (app *App) onAppStart(ctx Context) { + gsCtx := WithContext(ctx.Context(), ctx) for _, bean := range app.container.Dependencies(true) { x := bean.Value().Interface() if ae, ok := x.(AppEvent); ok { - ae.OnAppStart(ctx) + ae.OnAppStart(gsCtx) } } } -func (app *App) onAppStop(ctx context.Context) { +func (app *App) onAppStop(ctx Context) { + gsCtx := WithContext(context.Background(), ctx) for _, bean := range app.container.Dependencies(false) { x := bean.Value().Interface() if ae, ok := x.(AppEvent); ok { - ae.OnAppStop(ctx) + ae.OnAppStop(gsCtx) } } } @@ -184,7 +168,7 @@ func (app *App) Shutdown(msg ...string) { case <-app.exitChan: // app already closed default: - var logger = GetLogger("", utils.TypeName(app)) + var logger = GetLogger() logger.Info(fmt.Sprintf("program will exit %s", strings.Join(msg, ", "))) close(app.exitChan) } diff --git a/gs/gs.go b/gs/gs.go index 10df0979..67ae9eb0 100644 --- a/gs/gs.go +++ b/gs/gs.go @@ -81,8 +81,8 @@ type Context interface { type contextKey struct{} -func WithContext(ctx Context) context.Context { - return context.WithValue(ctx.Context(), contextKey{}, ctx) +func WithContext(parent context.Context, ctx Context) context.Context { + return context.WithValue(parent, contextKey{}, ctx) } func FromContext(ctx context.Context) Context { @@ -392,7 +392,7 @@ func (c *container) refresh(autoClear bool) (err error) { } c.state = Refreshing - c.logger = GetLogger("", utils.TypeName(c)) + c.logger = GetLogger() for _, b := range c.beans { c.registerBean(b) @@ -828,7 +828,7 @@ func (c *container) wireStruct(v reflect.Value, t reflect.Type, param conf.BindP tag = parseWireTag(tag).beanName } - l := GetLogger(tag, utils.TypeName(v)) + l := GetLogger(WithLogName(tag)) if nil == l { return fmt.Errorf("logger field %s not provide: %s", fieldPath, tag) } diff --git a/gs/gs_bean.go b/gs/gs_bean.go index b51ebdc6..be9c4044 100644 --- a/gs/gs_bean.go +++ b/gs/gs_bean.go @@ -301,7 +301,7 @@ func (d *BeanDefinition) constructor(ctx Context) error { fnValue := reflect.ValueOf(d.init) fnValues := []reflect.Value{d.Value()} if fnValue.Type().NumIn() > 1 { - fnValues = append(fnValues, reflect.ValueOf(WithContext(ctx))) + fnValues = append(fnValues, reflect.ValueOf(WithContext(ctx.Context(), ctx))) } out := fnValue.Call(fnValues) @@ -311,7 +311,7 @@ func (d *BeanDefinition) constructor(ctx Context) error { } if f, ok := d.Interface().(BeanInit); ok { - if err := f.OnInit(WithContext(ctx)); err != nil { + if err := f.OnInit(WithContext(ctx.Context(), ctx)); err != nil { return err } } diff --git a/gs/logger.go b/gs/logger.go index 6f8824c0..cc84d2b7 100644 --- a/gs/logger.go +++ b/gs/logger.go @@ -16,7 +16,9 @@ package gs -import "github.com/go-spring-projects/go-spring/internal/log" +import ( + "github.com/go-spring-projects/go-spring/internal/log" +) type Logger = log.Logger @@ -24,6 +26,22 @@ func SetLogger(loggerName string, logger *Logger, primary ...bool) { log.SetLogger(loggerName, logger, primary...) } -func GetLogger(loggerName string, typeName string) *Logger { - return log.GetLogger(loggerName, typeName) +func GetLogger(getOptions ...GetLogOption) *Logger { + options := &logOptions{} + for _, fn := range getOptions { + fn(options) + } + return log.GetLogger(options.loggerName) +} + +type GetLogOption func(*logOptions) + +type logOptions struct { + loggerName string +} + +func WithLogName(name string) GetLogOption { + return func(options *logOptions) { + options.loggerName = name + } } diff --git a/internal/log/logger.go b/internal/log/logger.go index d32fa944..ec0495b7 100644 --- a/internal/log/logger.go +++ b/internal/log/logger.go @@ -19,9 +19,9 @@ package log import ( "log/slog" "os" - "path/filepath" - "strings" "sync" + + "github.com/go-spring-projects/go-spring/internal/utils" ) type Logger = slog.Logger @@ -35,19 +35,8 @@ func init() { ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr { if slog.SourceKey == attr.Key { source := attr.Value.Any().(*slog.Source) - idx := strings.LastIndexByte(source.File, '/') - if idx == -1 { - return attr - } - // Find the penultimate separator. - idx = strings.LastIndexByte(source.File[:idx], '/') - if idx == -1 { - return attr - } - - source.File = source.File[idx+1:] + source.File = utils.StripTypeName(source.File) } - return attr }, } @@ -68,10 +57,10 @@ func SetLogger(loggerName string, logger *Logger, primary ...bool) { } } -func GetLogger(loggerName string, typeName string) *Logger { +func GetLogger(loggerName string) *Logger { if l, ok := loggers.Load(loggerName); ok { named := l.(*namedLogger) - return named.logger.With("logger", named.name, "type", filepath.Base(typeName)) + return named.logger.With("logger", named.name) } return nil } diff --git a/internal/utils/type.go b/internal/utils/type.go index 92741283..feaf0a6e 100644 --- a/internal/utils/type.go +++ b/internal/utils/type.go @@ -194,3 +194,17 @@ func IsBeanReceiver(t reflect.Type) bool { return IsBeanType(t) } } + +// StripTypeName returns simpled type name from full pkg path. +func StripTypeName(file string) string { + idx := strings.LastIndexByte(file, '/') + if idx == -1 { + return file + } + // Find the penultimate separator. + idx = strings.LastIndexByte(file[:idx], '/') + if idx == -1 { + return file + } + return file[idx+1:] +} diff --git a/internal/utils/type_test.go b/internal/utils/type_test.go index 4900adbe..5633adc9 100644 --- a/internal/utils/type_test.go +++ b/internal/utils/type_test.go @@ -564,3 +564,11 @@ func TestIsBeanReceiver(t *testing.T) { assert.False(t, IsBeanReceiver(reflect.TypeOf(map[string]*string{}))) assert.True(t, IsBeanReceiver(reflect.TypeOf(map[string]fmt.Stringer{}))) } + +func TestStripTypeNameFromFile(t *testing.T) { + assert.Equal(t, StripTypeName("test.go"), "test.go") + assert.Equal(t, StripTypeName("xx_test.go"), "xx_test.go") + assert.Equal(t, StripTypeName("bar/test.go"), "bar/test.go") + assert.Equal(t, StripTypeName("foo/bar/test.go"), "bar/test.go") + assert.Equal(t, StripTypeName("github.com/foo/bar/test.go"), "bar/test.go") +}