Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"}
```

### 依赖序事件
Expand Down
34 changes: 9 additions & 25 deletions gs/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)

Expand All @@ -105,7 +97,7 @@ func (app *App) run(resourceLocator ResourceLocator) error {

<-app.exitChan

app.onAppStop(context.Background())
app.onAppStop(app.container)

app.container.Close()

Expand All @@ -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)
}
}
}
Expand Down Expand Up @@ -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)
}
Expand Down
8 changes: 4 additions & 4 deletions gs/gs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions gs/gs_bean.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
}
}
Expand Down
24 changes: 21 additions & 3 deletions gs/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,32 @@

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

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
}
}
21 changes: 5 additions & 16 deletions internal/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
},
}
Expand All @@ -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
}
14 changes: 14 additions & 0 deletions internal/utils/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:]
}
8 changes: 8 additions & 0 deletions internal/utils/type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}