micro/server/hooks.go

45 lines
1.0 KiB
Go
Raw Normal View History

2024-11-24 01:15:07 +03:00
package server
import (
"context"
"strings"
"go.unistack.org/micro/v3/logger"
"go.unistack.org/micro/v3/metadata"
)
func NewLoggerHookSubHandler(extractKeys ...string) HookSubHandler {
return func(next FuncSubHandler) FuncSubHandler {
return func(ctx context.Context, msg Message) (err error) {
log := logger.MustContext(ctx)
attrs := []interface{}{"endpoint", msg.Topic()}
if md, ok := metadata.FromIncomingContext(ctx); ok {
for idx := range extractKeys {
if val, ok := md.Get(extractKeys[idx]); ok {
attrs = append(attrs, strings.ToLower(extractKeys[idx]), val)
}
}
}
log = log.Fields(attrs...)
ctx = logger.NewContext(ctx, log)
if log.V(logger.DebugLevel) {
log.Fields(
// "payload", MarshalJSON(msg.Body()),
"headers", msg.Header(),
).Debug(ctx, "subscriber called")
}
if err = next(ctx, msg); err != nil {
log.Error(ctx, "subscriber finished with error", err)
} else {
log.Debug(ctx, "subscriber finished")
}
return err
}
}
}