log: remove component logger to use global logger (#2061)

* remove component logger to user global logger
status-code-override
Tony Chen 3 years ago committed by chenzhihui
parent ebf78ce69f
commit 2dd247be8f
  1. 22
      config/config.go
  2. 5
      config/config_test.go
  3. 6
      config/options.go
  4. 4
      config/reader.go
  5. 5
      contrib/config/apollo/README.md
  6. 28
      contrib/config/apollo/apollo.go
  7. 18
      contrib/config/apollo/watcher.go
  8. 5
      contrib/registry/discovery/README.md
  9. 43
      contrib/registry/discovery/discovery.go
  10. 11
      contrib/registry/discovery/impl_registrar.go
  11. 42
      log/global.go
  12. 4
      log/value.go
  13. 10
      middleware/recovery/recovery.go
  14. 3
      middleware/recovery/recovery_test.go
  15. 8
      transport/grpc/client.go
  16. 11
      transport/grpc/client_test.go
  17. 11
      transport/grpc/resolver/discovery/builder.go
  18. 19
      transport/grpc/resolver/discovery/builder_test.go
  19. 17
      transport/grpc/resolver/discovery/resolver.go
  20. 4
      transport/grpc/resolver/discovery/resolver_test.go
  21. 11
      transport/grpc/server.go
  22. 30
      transport/grpc/server_test.go
  23. 14
      transport/http/resolver.go
  24. 11
      transport/http/server.go

@ -7,13 +7,12 @@ import (
"sync" "sync"
"time" "time"
"github.com/go-kratos/kratos/v2/log"
// init encoding // init encoding
_ "github.com/go-kratos/kratos/v2/encoding/json" _ "github.com/go-kratos/kratos/v2/encoding/json"
_ "github.com/go-kratos/kratos/v2/encoding/proto" _ "github.com/go-kratos/kratos/v2/encoding/proto"
_ "github.com/go-kratos/kratos/v2/encoding/xml" _ "github.com/go-kratos/kratos/v2/encoding/xml"
_ "github.com/go-kratos/kratos/v2/encoding/yaml" _ "github.com/go-kratos/kratos/v2/encoding/yaml"
"github.com/go-kratos/kratos/v2/log"
) )
var ( var (
@ -43,13 +42,11 @@ type config struct {
cached sync.Map cached sync.Map
observers sync.Map observers sync.Map
watchers []Watcher watchers []Watcher
log *log.Helper
} }
// New new a config with options. // New new a config with options.
func New(opts ...Option) Config { func New(opts ...Option) Config {
o := options{ o := options{
logger: log.GetLogger(),
decoder: defaultDecoder, decoder: defaultDecoder,
resolver: defaultResolver, resolver: defaultResolver,
} }
@ -59,7 +56,6 @@ func New(opts ...Option) Config {
return &config{ return &config{
opts: o, opts: o,
reader: newReader(o), reader: newReader(o),
log: log.NewHelper(o.logger),
} }
} }
@ -67,20 +63,20 @@ func (c *config) watch(w Watcher) {
for { for {
kvs, err := w.Next() kvs, err := w.Next()
if errors.Is(err, context.Canceled) { if errors.Is(err, context.Canceled) {
c.log.Infof("watcher's ctx cancel : %v", err) log.Infof("watcher's ctx cancel : %v", err)
return return
} }
if err != nil { if err != nil {
time.Sleep(time.Second) time.Sleep(time.Second)
c.log.Errorf("failed to watch next config: %v", err) log.Errorf("failed to watch next config: %v", err)
continue continue
} }
if err := c.reader.Merge(kvs...); err != nil { if err := c.reader.Merge(kvs...); err != nil {
c.log.Errorf("failed to merge next config: %v", err) log.Errorf("failed to merge next config: %v", err)
continue continue
} }
if err := c.reader.Resolve(); err != nil { if err := c.reader.Resolve(); err != nil {
c.log.Errorf("failed to resolve next config: %v", err) log.Errorf("failed to resolve next config: %v", err)
continue continue
} }
c.cached.Range(func(key, value interface{}) bool { c.cached.Range(func(key, value interface{}) bool {
@ -104,22 +100,22 @@ func (c *config) Load() error {
return err return err
} }
for _, v := range kvs { for _, v := range kvs {
c.log.Debugf("config loaded: %s format: %s", v.Key, v.Format) log.Debugf("config loaded: %s format: %s", v.Key, v.Format)
} }
if err = c.reader.Merge(kvs...); err != nil { if err = c.reader.Merge(kvs...); err != nil {
c.log.Errorf("failed to merge config source: %v", err) log.Errorf("failed to merge config source: %v", err)
return err return err
} }
w, err := src.Watch() w, err := src.Watch()
if err != nil { if err != nil {
c.log.Errorf("failed to watch config source: %v", err) log.Errorf("failed to watch config source: %v", err)
return err return err
} }
c.watchers = append(c.watchers, w) c.watchers = append(c.watchers, w)
go c.watch(w) go c.watch(w)
} }
if err := c.reader.Resolve(); err != nil { if err := c.reader.Resolve(); err != nil {
c.log.Errorf("failed to resolve config source: %v", err) log.Errorf("failed to resolve config source: %v", err)
return err return err
} }
return nil return nil

@ -4,8 +4,6 @@ import (
"errors" "errors"
"reflect" "reflect"
"testing" "testing"
"github.com/go-kratos/kratos/v2/log"
) )
const ( const (
@ -123,7 +121,6 @@ func TestConfig(t *testing.T) {
WithSource(newTestJSONSource(_testJSON)), WithSource(newTestJSONSource(_testJSON)),
WithDecoder(defaultDecoder), WithDecoder(defaultDecoder),
WithResolver(defaultResolver), WithResolver(defaultResolver),
WithLogger(log.GetLogger()),
) )
err = c.Close() err = c.Close()
if err != nil { if err != nil {
@ -135,12 +132,10 @@ func TestConfig(t *testing.T) {
sources: []Source{jSource}, sources: []Source{jSource},
decoder: defaultDecoder, decoder: defaultDecoder,
resolver: defaultResolver, resolver: defaultResolver,
logger: log.GetLogger(),
} }
cf := &config{} cf := &config{}
cf.opts = opts cf.opts = opts
cf.reader = newReader(opts) cf.reader = newReader(opts)
cf.log = log.NewHelper(opts.logger)
err = cf.Load() err = cf.Load()
if err != nil { if err != nil {

@ -22,7 +22,6 @@ type options struct {
sources []Source sources []Source
decoder Decoder decoder Decoder
resolver Resolver resolver Resolver
logger log.Logger
} }
// WithSource with config source. // WithSource with config source.
@ -51,10 +50,9 @@ func WithResolver(r Resolver) Option {
} }
// WithLogger with config logger. // WithLogger with config logger.
// Deprecated: use global logger instead.
func WithLogger(l log.Logger) Option { func WithLogger(l log.Logger) Option {
return func(o *options) { return func(o *options) {}
o.logger = l
}
} }
// defaultDecoder decode config from source KeyValue // defaultDecoder decode config from source KeyValue

@ -47,11 +47,11 @@ func (r *reader) Merge(kvs ...*KeyValue) error {
for _, kv := range kvs { for _, kv := range kvs {
next := make(map[string]interface{}) next := make(map[string]interface{})
if err := r.opts.decoder(kv, next); err != nil { if err := r.opts.decoder(kv, next); err != nil {
_ = log.GetLogger().Log(log.LevelError, fmt.Sprintf("config decode error, err: %v, key: %s, value: %s", err, kv.Key, string(kv.Value))) log.Errorf("Failed to config decode error: %v key: %s value: %s", err, kv.Key, string(kv.Value))
return err return err
} }
if err := mergo.Map(&merged, convertMap(next), mergo.WithOverride); err != nil { if err := mergo.Map(&merged, convertMap(next), mergo.WithOverride); err != nil {
_ = log.GetLogger().Log(log.LevelError, fmt.Sprintf("config merge error, err: %v, key: %s, value: %s", err, kv.Key, string(kv.Value))) log.Errorf("Failed to config merge error: %v key: %s value: %s", err, kv.Key, string(kv.Value))
return err return err
} }
} }

@ -55,9 +55,6 @@ func WithEnableBackup() Option
// specify apollo endpoint, such as http://localhost:8080 // specify apollo endpoint, such as http://localhost:8080
func WithEndpoint(endpoint string) Option func WithEndpoint(endpoint string) Option
// inject a logger to debug
func WithLogger(logger log.Logger) Option
// namespaces to load, comma to separate. // namespaces to load, comma to separate.
func WithNamespace(name string) Option func WithNamespace(name string) Option
@ -101,4 +98,4 @@ config := map[string]interface{}{
} }
} }
_ = config _ = config
``` ```

@ -1,7 +1,6 @@
package apollo package apollo
import ( import (
"fmt"
"strings" "strings"
"github.com/go-kratos/kratos/v2/config" "github.com/go-kratos/kratos/v2/config"
@ -28,8 +27,6 @@ type options struct {
namespace string namespace string
isBackupConfig bool isBackupConfig bool
backupPath string backupPath string
logger log.Logger
} }
// WithAppID with apollo config app id // WithAppID with apollo config app id
@ -88,19 +85,8 @@ func WithBackupPath(backupPath string) Option {
} }
} }
// WithLogger use custom logger to replace default logger.
func WithLogger(logger log.Logger) Option {
return func(o *options) {
if logger != nil {
o.logger = logger
}
}
}
func NewSource(opts ...Option) config.Source { func NewSource(opts ...Option) config.Source {
op := options{ op := options{}
logger: log.GetLogger(),
}
for _, o := range opts { for _, o := range opts {
o(&op) o(&op)
} }
@ -167,10 +153,7 @@ func resolve(key string, value interface{}, target map[string]interface{}) {
// current exists, then check existing value type, if it's not map // current exists, then check existing value type, if it's not map
// that means duplicate keys, and at least one is not map instance. // that means duplicate keys, and at least one is not map instance.
if cursor, ok = v.(map[string]interface{}); !ok { if cursor, ok = v.(map[string]interface{}); !ok {
_ = log.GetLogger().Log(log.LevelWarn, log.Warnf("duplicate key: %v\n", strings.Join(keys[:i+1], "."))
"msg",
fmt.Sprintf("duplicate key: %v\n", strings.Join(keys[:i+1], ".")),
)
break break
} }
} }
@ -202,10 +185,7 @@ func (e *apollo) load() []*config.KeyValue {
codec := encoding.GetCodec(f) codec := encoding.GetCodec(f)
val, err := codec.Marshal(next) val, err := codec.Marshal(next)
if err != nil { if err != nil {
_ = e.opt.logger.Log(log.LevelWarn, log.Warnf("apollo could not handle namespace %s: %v", ns, err)
"msg",
fmt.Sprintf("apollo could not handle namespace %s: %v", ns, err),
)
continue continue
} }
@ -224,7 +204,7 @@ func (e *apollo) Load() (kv []*config.KeyValue, err error) {
} }
func (e *apollo) Watch() (config.Watcher, error) { func (e *apollo) Watch() (config.Watcher, error) {
w, err := newWatcher(e, e.opt.logger) w, err := newWatcher(e)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -2,7 +2,6 @@ package apollo
import ( import (
"context" "context"
"fmt"
"github.com/go-kratos/kratos/v2/config" "github.com/go-kratos/kratos/v2/config"
"github.com/go-kratos/kratos/v2/encoding" "github.com/go-kratos/kratos/v2/encoding"
@ -17,8 +16,7 @@ type watcher struct {
} }
type customChangeListener struct { type customChangeListener struct {
in chan<- []*config.KeyValue in chan<- []*config.KeyValue
logger log.Logger
} }
func (c *customChangeListener) onChange(namespace string, changes map[string]*storage.ConfigChange) []*config.KeyValue { func (c *customChangeListener) onChange(namespace string, changes map[string]*storage.ConfigChange) []*config.KeyValue {
@ -33,10 +31,7 @@ func (c *customChangeListener) onChange(namespace string, changes map[string]*st
codec := encoding.GetCodec(f) codec := encoding.GetCodec(f)
val, err := codec.Marshal(next) val, err := codec.Marshal(next)
if err != nil { if err != nil {
_ = c.logger.Log(log.LevelWarn, log.Warnf("apollo could not handle namespace %s: %v", namespace, err)
"msg",
fmt.Sprintf("apollo could not handle namespace %s: %v", namespace, err),
)
return nil return nil
} }
kv = append(kv, &config.KeyValue{ kv = append(kv, &config.KeyValue{
@ -59,15 +54,10 @@ func (c *customChangeListener) OnChange(changeEvent *storage.ChangeEvent) {
func (c *customChangeListener) OnNewestChange(changeEvent *storage.FullChangeEvent) {} func (c *customChangeListener) OnNewestChange(changeEvent *storage.FullChangeEvent) {}
func newWatcher(a *apollo, logger log.Logger) (config.Watcher, error) { func newWatcher(a *apollo) (config.Watcher, error) {
if logger == nil {
logger = log.GetLogger()
}
changeCh := make(chan []*config.KeyValue) changeCh := make(chan []*config.KeyValue)
listener := &customChangeListener{in: changeCh, logger: logger} listener := &customChangeListener{in: changeCh}
a.client.AddChangeListener(listener) a.client.AddChangeListener(listener)
return &watcher{ return &watcher{
out: changeCh, out: changeCh,
cancelFn: func() { cancelFn: func() {

@ -14,9 +14,6 @@ import (
) )
func main() { func main() {
logger := log.NewStdLogger(os.Stdout)
logger = log.With(logger, "service", "example.registry.discovery")
// initialize a registry // initialize a registry
r := discovery.New(&discovery.Config{ r := discovery.New(&discovery.Config{
Nodes: []string{"0.0.0.0:7171"}, Nodes: []string{"0.0.0.0:7171"},
@ -24,7 +21,7 @@ func main() {
Region: "sh1", Region: "sh1",
Zone: "zone1", Zone: "zone1",
Host: "hostname", Host: "hostname",
}, logger) })
// construct srv instance // construct srv instance
// ... // ...

@ -5,16 +5,14 @@ import (
"fmt" "fmt"
"math/rand" "math/rand"
"net/url" "net/url"
"os"
"strconv" "strconv"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-resty/resty/v2" "github.com/go-resty/resty/v2"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/go-kratos/kratos/v2/log"
) )
type Discovery struct { type Discovery struct {
@ -32,8 +30,6 @@ type Discovery struct {
registry map[string]struct{} registry map[string]struct{}
lastHost string lastHost string
cancelPolls context.CancelFunc cancelPolls context.CancelFunc
logger log.Logger
} }
type appInfo struct { type appInfo struct {
@ -44,15 +40,7 @@ type appInfo struct {
// New construct a Discovery instance which implements registry.Registrar, // New construct a Discovery instance which implements registry.Registrar,
// registry.Discovery and registry.Watcher. // registry.Discovery and registry.Watcher.
func New(c *Config, logger log.Logger) *Discovery { func New(c *Config) *Discovery {
if logger == nil {
logger = log.NewStdLogger(os.Stdout)
logger = log.With(logger,
"registry.pluginName", "Discovery",
"ts", log.DefaultTimestamp,
"caller", log.DefaultCaller,
)
}
if c == nil { if c == nil {
c = new(Config) c = new(Config)
} }
@ -66,7 +54,6 @@ func New(c *Config, logger log.Logger) *Discovery {
cancelFunc: cancel, cancelFunc: cancel,
apps: map[string]*appInfo{}, apps: map[string]*appInfo{},
registry: map[string]struct{}{}, registry: map[string]struct{}{},
logger: logger,
} }
d.httpClient = resty.New(). d.httpClient = resty.New().
@ -94,10 +81,6 @@ func (d *Discovery) Close() error {
return nil return nil
} }
func (d *Discovery) Logger() *log.Helper {
return log.NewHelper(d.logger)
}
// selfProc start a goroutine to refresh Discovery self registration information. // selfProc start a goroutine to refresh Discovery self registration information.
func (d *Discovery) selfProc(resolver *Resolve, event <-chan struct{}) { func (d *Discovery) selfProc(resolver *Resolve, event <-chan struct{}) {
for { for {
@ -178,7 +161,7 @@ func (d *Discovery) resolveBuild(appID string) *Resolve {
} }
} }
d.Logger().Debugf("Discovery: AddWatch(%s) already watch(%v)", appID, ok) log.Debugf("Discovery: AddWatch(%s) already watch(%v)", appID, ok)
d.once.Do(func() { d.once.Do(func() {
go d.serverProc() go d.serverProc()
}) })
@ -186,7 +169,7 @@ func (d *Discovery) resolveBuild(appID string) *Resolve {
} }
func (d *Discovery) serverProc() { func (d *Discovery) serverProc() {
defer d.Logger().Debug("Discovery serverProc quit") defer log.Debug("Discovery serverProc quit")
var ( var (
retry int retry int
@ -242,8 +225,6 @@ func (d *Discovery) switchNode() {
// renew an instance with Discovery // renew an instance with Discovery
func (d *Discovery) renew(ctx context.Context, ins *discoveryInstance) (err error) { func (d *Discovery) renew(ctx context.Context, ins *discoveryInstance) (err error) {
// d.Logger().Debug("Discovery:renew renew calling")
d.mutex.RLock() d.mutex.RLock()
c := d.config c := d.config
d.mutex.RUnlock() d.mutex.RUnlock()
@ -262,7 +243,7 @@ func (d *Discovery) renew(ctx context.Context, ins *discoveryInstance) (err erro
SetResult(&res). SetResult(&res).
Post(uri); err != nil { Post(uri); err != nil {
d.switchNode() d.switchNode()
d.Logger().Errorf("Discovery: renew client.Get(%v) env(%s) appid(%s) hostname(%s) error(%v)", log.Errorf("Discovery: renew client.Get(%v) env(%s) appid(%s) hostname(%s) error(%v)",
uri, c.Env, ins.AppID, c.Host, err) uri, c.Env, ins.AppID, c.Host, err)
return return
} }
@ -276,7 +257,7 @@ func (d *Discovery) renew(ctx context.Context, ins *discoveryInstance) (err erro
return return
} }
d.Logger().Errorf( log.Errorf(
"Discovery: renew client.Get(%v) env(%s) appid(%s) hostname(%s) code(%v)", "Discovery: renew client.Get(%v) env(%s) appid(%s) hostname(%s) code(%v)",
uri, c.Env, ins.AppID, c.Host, res.Code, uri, c.Env, ins.AppID, c.Host, res.Code,
) )
@ -304,7 +285,7 @@ func (d *Discovery) cancel(ins *discoveryInstance) (err error) {
SetResult(&res). SetResult(&res).
Post(uri); err != nil { Post(uri); err != nil {
d.switchNode() d.switchNode()
d.Logger().Errorf("Discovery cancel client.Get(%v) env(%s) appid(%s) hostname(%s) error(%v)", log.Errorf("Discovery cancel client.Get(%v) env(%s) appid(%s) hostname(%s) error(%v)",
uri, config.Env, ins.AppID, config.Host, err) uri, config.Env, ins.AppID, config.Host, err)
return return
} }
@ -315,7 +296,7 @@ func (d *Discovery) cancel(ins *discoveryInstance) (err error) {
return nil return nil
} }
d.Logger().Warnf("Discovery cancel client.Get(%v) env(%s) appid(%s) hostname(%s) code(%v)", log.Warnf("Discovery cancel client.Get(%v) env(%s) appid(%s) hostname(%s) code(%v)",
uri, config.Env, ins.AppID, config.Host, res.Code) uri, config.Env, ins.AppID, config.Host, res.Code)
err = fmt.Errorf("ErrorCode: %d", res.Code) err = fmt.Errorf("ErrorCode: %d", res.Code)
return return
@ -407,13 +388,13 @@ func (d *Discovery) polls(ctx context.Context) (apps map[string]*disInstancesInf
SetQueryParamsFromValues(p). SetQueryParamsFromValues(p).
SetResult(res).Get(uri); err != nil { SetResult(res).Get(uri); err != nil {
d.switchNode() d.switchNode()
d.Logger().Errorf("Discovery: client.Get(%s) error(%+v)", reqURI, err) log.Errorf("Discovery: client.Get(%s) error(%+v)", reqURI, err)
return nil, err return nil, err
} }
if res.Code != _codeOK { if res.Code != _codeOK {
if res.Code != _codeNotModified { if res.Code != _codeNotModified {
d.Logger().Errorf("Discovery: client.Get(%s) get error code(%d)", reqURI, res.Code) log.Errorf("Discovery: client.Get(%s) get error code(%d)", reqURI, res.Code)
} }
err = fmt.Errorf("discovery.polls failed ErrCode: %d", res.Code) err = fmt.Errorf("discovery.polls failed ErrCode: %d", res.Code)
return return
@ -422,12 +403,12 @@ func (d *Discovery) polls(ctx context.Context) (apps map[string]*disInstancesInf
for _, app := range res.Data { for _, app := range res.Data {
if app.LastTs == 0 { if app.LastTs == 0 {
err = ErrServerError err = ErrServerError
d.Logger().Errorf("Discovery: client.Get(%s) latest_timestamp is 0, instances:(%+v)", reqURI, res.Data) log.Errorf("Discovery: client.Get(%s) latest_timestamp is 0, instances:(%+v)", reqURI, res.Data)
return return
} }
} }
d.Logger().Debugf("Discovery: successfully polls(%s) instances (%+v)", reqURI, res.Data) log.Debugf("Discovery: successfully polls(%s) instances (%+v)", reqURI, res.Data)
apps = res.Data apps = res.Data
return return
} }

@ -9,6 +9,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/registry" "github.com/go-kratos/kratos/v2/registry"
) )
@ -43,7 +44,7 @@ func (d *Discovery) Register(ctx context.Context, service *registry.ServiceInsta
// renew the current register_service // renew the current register_service
go func() { go func() {
defer d.Logger().Warn("Discovery:register_service goroutine quit") defer log.Warn("Discovery:register_service goroutine quit")
ticker := time.NewTicker(_registerGap) ticker := time.NewTicker(_registerGap)
defer ticker.Stop() defer ticker.Stop()
for { for {
@ -70,7 +71,7 @@ func (d *Discovery) register(ctx context.Context, ins *discoveryInstance) (err e
var metadata []byte var metadata []byte
if ins.Metadata != nil { if ins.Metadata != nil {
if metadata, err = json.Marshal(ins.Metadata); err != nil { if metadata, err = json.Marshal(ins.Metadata); err != nil {
d.Logger().Errorf( log.Errorf(
"Discovery:register instance Marshal metadata(%v) failed!error(%v)", ins.Metadata, err, "Discovery:register instance Marshal metadata(%v) failed!error(%v)", ins.Metadata, err,
) )
} }
@ -102,18 +103,18 @@ func (d *Discovery) register(ctx context.Context, ins *discoveryInstance) (err e
SetResult(&res). SetResult(&res).
Post(uri); err != nil { Post(uri); err != nil {
d.switchNode() d.switchNode()
d.Logger().Errorf("Discovery: register client.Get(%s) zone(%s) env(%s) appid(%s) addrs(%v) error(%v)", log.Errorf("Discovery: register client.Get(%s) zone(%s) env(%s) appid(%s) addrs(%v) error(%v)",
uri+"?"+p.Encode(), c.Zone, c.Env, ins.AppID, ins.Addrs, err) uri+"?"+p.Encode(), c.Zone, c.Env, ins.AppID, ins.Addrs, err)
return return
} }
if res.Code != 0 { if res.Code != 0 {
err = fmt.Errorf("ErrorCode: %d", res.Code) err = fmt.Errorf("ErrorCode: %d", res.Code)
d.Logger().Errorf("Discovery: register client.Get(%v) env(%s) appid(%s) addrs(%v) code(%v)", log.Errorf("Discovery: register client.Get(%v) env(%s) appid(%s) addrs(%v) code(%v)",
uri, c.Env, ins.AppID, ins.Addrs, res.Code) uri, c.Env, ins.AppID, ins.Addrs, res.Code)
} }
d.Logger().Infof( log.Infof(
"Discovery: register client.Get(%v) env(%s) appid(%s) addrs(%s) success\n", "Discovery: register client.Get(%v) env(%s) appid(%s) addrs(%s) success\n",
uri, c.Env, ins.AppID, ins.Addrs, uri, c.Env, ins.AppID, ins.Addrs,
) )

@ -2,6 +2,8 @@ package log
import ( import (
"context" "context"
"fmt"
"os"
"sync" "sync"
) )
@ -13,7 +15,6 @@ var global = &loggerAppliance{}
type loggerAppliance struct { type loggerAppliance struct {
lock sync.Mutex lock sync.Mutex
Logger Logger
helper *Helper
} }
func init() { func init() {
@ -24,7 +25,6 @@ func (a *loggerAppliance) SetLogger(in Logger) {
a.lock.Lock() a.lock.Lock()
defer a.lock.Unlock() defer a.lock.Unlock()
a.Logger = in a.Logger = in
a.helper = NewHelper(a.Logger)
} }
func (a *loggerAppliance) GetLogger() Logger { func (a *loggerAppliance) GetLogger() Logger {
@ -44,84 +44,88 @@ func GetLogger() Logger {
// Log Print log by level and keyvals. // Log Print log by level and keyvals.
func Log(level Level, keyvals ...interface{}) { func Log(level Level, keyvals ...interface{}) {
global.helper.Log(level, keyvals...) _ = global.Log(level, keyvals...)
} }
// Context with context logger.
func Context(ctx context.Context) *Helper { func Context(ctx context.Context) *Helper {
return global.helper.WithContext(ctx) return NewHelper(WithContext(ctx, global))
} }
// Debug logs a message at debug level. // Debug logs a message at debug level.
func Debug(a ...interface{}) { func Debug(a ...interface{}) {
global.helper.Debug(a...) _ = global.Log(LevelDebug, DefaultMessageKey, fmt.Sprint(a...))
} }
// Debugf logs a message at debug level. // Debugf logs a message at debug level.
func Debugf(format string, a ...interface{}) { func Debugf(format string, a ...interface{}) {
global.helper.Debugf(format, a...) _ = global.Log(LevelDebug, DefaultMessageKey, fmt.Sprintf(format, a...))
} }
// Debugw logs a message at debug level. // Debugw logs a message at debug level.
func Debugw(keyvals ...interface{}) { func Debugw(keyvals ...interface{}) {
global.helper.Debugw(keyvals...) _ = global.Log(LevelDebug, keyvals...)
} }
// Info logs a message at info level. // Info logs a message at info level.
func Info(a ...interface{}) { func Info(a ...interface{}) {
global.helper.Info(a...) _ = global.Log(LevelInfo, DefaultMessageKey, fmt.Sprint(a...))
} }
// Infof logs a message at info level. // Infof logs a message at info level.
func Infof(format string, a ...interface{}) { func Infof(format string, a ...interface{}) {
global.helper.Infof(format, a...) _ = global.Log(LevelInfo, DefaultMessageKey, fmt.Sprintf(format, a...))
} }
// Infow logs a message at info level. // Infow logs a message at info level.
func Infow(keyvals ...interface{}) { func Infow(keyvals ...interface{}) {
global.helper.Infow(keyvals...) _ = global.Log(LevelInfo, keyvals...)
} }
// Warn logs a message at warn level. // Warn logs a message at warn level.
func Warn(a ...interface{}) { func Warn(a ...interface{}) {
global.helper.Warn(a...) _ = global.Log(LevelWarn, DefaultMessageKey, fmt.Sprint(a...))
} }
// Warnf logs a message at warnf level. // Warnf logs a message at warnf level.
func Warnf(format string, a ...interface{}) { func Warnf(format string, a ...interface{}) {
global.helper.Warnf(format, a...) _ = global.Log(LevelWarn, DefaultMessageKey, fmt.Sprintf(format, a...))
} }
// Warnw logs a message at warnf level. // Warnw logs a message at warnf level.
func Warnw(keyvals ...interface{}) { func Warnw(keyvals ...interface{}) {
global.helper.Warnw(keyvals...) _ = global.Log(LevelWarn, keyvals...)
} }
// Error logs a message at error level. // Error logs a message at error level.
func Error(a ...interface{}) { func Error(a ...interface{}) {
global.helper.Error(a...) _ = global.Log(LevelError, DefaultMessageKey, fmt.Sprint(a...))
} }
// Errorf logs a message at error level. // Errorf logs a message at error level.
func Errorf(format string, a ...interface{}) { func Errorf(format string, a ...interface{}) {
global.helper.Errorf(format, a...) _ = global.Log(LevelError, DefaultMessageKey, fmt.Sprintf(format, a...))
} }
// Errorw logs a message at error level. // Errorw logs a message at error level.
func Errorw(keyvals ...interface{}) { func Errorw(keyvals ...interface{}) {
global.helper.Errorw(keyvals...) _ = global.Log(LevelError, keyvals...)
} }
// Fatal logs a message at fatal level. // Fatal logs a message at fatal level.
func Fatal(a ...interface{}) { func Fatal(a ...interface{}) {
global.helper.Fatal(a...) _ = global.Log(LevelFatal, DefaultMessageKey, fmt.Sprint(a...))
os.Exit(1)
} }
// Fatalf logs a message at fatal level. // Fatalf logs a message at fatal level.
func Fatalf(format string, a ...interface{}) { func Fatalf(format string, a ...interface{}) {
global.helper.Fatalf(format, a...) _ = global.Log(LevelFatal, DefaultMessageKey, fmt.Sprintf(format, a...))
os.Exit(1)
} }
// Fatalw logs a message at fatal level. // Fatalw logs a message at fatal level.
func Fatalw(keyvals ...interface{}) { func Fatalw(keyvals ...interface{}) {
global.helper.Fatalw(keyvals...) _ = global.Log(LevelFatal, keyvals...)
os.Exit(1)
} }

@ -40,6 +40,10 @@ func Caller(depth int) Valuer {
d++ d++
_, file, line, _ = runtime.Caller(d) _, file, line, _ = runtime.Caller(d)
} }
if strings.LastIndex(file, "/log/global.go") > 0 {
d++
_, file, line, _ = runtime.Caller(d)
}
idx := strings.LastIndexByte(file, '/') idx := strings.LastIndexByte(file, '/')
return file[idx+1:] + ":" + strconv.Itoa(line) return file[idx+1:] + ":" + strconv.Itoa(line)
} }

@ -20,7 +20,6 @@ type Option func(*options)
type options struct { type options struct {
handler HandlerFunc handler HandlerFunc
logger log.Logger
} }
// WithHandler with recovery handler. // WithHandler with recovery handler.
@ -31,16 +30,14 @@ func WithHandler(h HandlerFunc) Option {
} }
// WithLogger with recovery logger. // WithLogger with recovery logger.
// Deprecated: use global logger instead.
func WithLogger(logger log.Logger) Option { func WithLogger(logger log.Logger) Option {
return func(o *options) { return func(o *options) {}
o.logger = logger
}
} }
// Recovery is a server middleware that recovers from any panics. // Recovery is a server middleware that recovers from any panics.
func Recovery(opts ...Option) middleware.Middleware { func Recovery(opts ...Option) middleware.Middleware {
op := options{ op := options{
logger: log.GetLogger(),
handler: func(ctx context.Context, req, err interface{}) error { handler: func(ctx context.Context, req, err interface{}) error {
return ErrUnknownRequest return ErrUnknownRequest
}, },
@ -48,7 +45,6 @@ func Recovery(opts ...Option) middleware.Middleware {
for _, o := range opts { for _, o := range opts {
o(&op) o(&op)
} }
logger := log.NewHelper(op.logger)
return func(handler middleware.Handler) middleware.Handler { return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) { return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
defer func() { defer func() {
@ -56,7 +52,7 @@ func Recovery(opts ...Option) middleware.Middleware {
buf := make([]byte, 64<<10) //nolint:gomnd buf := make([]byte, 64<<10) //nolint:gomnd
n := runtime.Stack(buf, false) n := runtime.Stack(buf, false)
buf = buf[:n] buf = buf[:n]
logger.WithContext(ctx).Errorf("%v: %+v\n%s\n", rerr, req, buf) log.Context(ctx).Errorf("%v: %+v\n%s\n", rerr, req, buf)
err = op.handler(ctx, req, rerr) err = op.handler(ctx, req, rerr)
} }

@ -6,7 +6,6 @@ import (
"testing" "testing"
"github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/log"
) )
func TestOnce(t *testing.T) { func TestOnce(t *testing.T) {
@ -19,7 +18,7 @@ func TestOnce(t *testing.T) {
next := func(ctx context.Context, req interface{}) (interface{}, error) { next := func(ctx context.Context, req interface{}) (interface{}, error) {
panic("panic reason") panic("panic reason")
} }
_, e := Recovery(WithLogger(log.GetLogger()))(next)(context.Background(), "panic") _, e := Recovery()(next)(context.Background(), "panic")
t.Logf("succ and reason is %v", e) t.Logf("succ and reason is %v", e)
} }

@ -90,10 +90,9 @@ func WithFilter(filters ...selector.Filter) ClientOption {
} }
// WithLogger with logger // WithLogger with logger
// Deprecated: use global logger instead.
func WithLogger(log log.Logger) ClientOption { func WithLogger(log log.Logger) ClientOption {
return func(o *clientOptions) { return func(o *clientOptions) {}
o.logger = log
}
} }
// clientOptions is gRPC Client // clientOptions is gRPC Client
@ -107,7 +106,6 @@ type clientOptions struct {
grpcOpts []grpc.DialOption grpcOpts []grpc.DialOption
balancerName string balancerName string
filters []selector.Filter filters []selector.Filter
logger log.Logger
} }
// Dial returns a GRPC connection. // Dial returns a GRPC connection.
@ -124,7 +122,6 @@ func dial(ctx context.Context, insecure bool, opts ...ClientOption) (*grpc.Clien
options := clientOptions{ options := clientOptions{
timeout: 2000 * time.Millisecond, timeout: 2000 * time.Millisecond,
balancerName: wrr.Name, balancerName: wrr.Name,
logger: log.GetLogger(),
} }
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
@ -145,7 +142,6 @@ func dial(ctx context.Context, insecure bool, opts ...ClientOption) (*grpc.Clien
discovery.NewBuilder( discovery.NewBuilder(
options.discovery, options.discovery,
discovery.WithInsecure(insecure), discovery.WithInsecure(insecure),
discovery.WithLogger(options.logger),
))) )))
} }
if insecure { if insecure {

@ -7,7 +7,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware" "github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/registry" "github.com/go-kratos/kratos/v2/registry"
"google.golang.org/grpc" "google.golang.org/grpc"
@ -70,15 +69,6 @@ func TestWithTLSConfig(t *testing.T) {
} }
} }
func TestWithLogger(t *testing.T) {
o := &clientOptions{}
v := log.DefaultLogger
WithLogger(v)(o)
if !reflect.DeepEqual(v, o.logger) {
t.Errorf("expect %v but got %v", v, o.logger)
}
}
func EmptyMiddleware() middleware.Middleware { func EmptyMiddleware() middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler { return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) { return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
@ -145,7 +135,6 @@ func TestDialConn(t *testing.T) {
true, true,
WithDiscovery(&mockRegistry{}), WithDiscovery(&mockRegistry{}),
WithTimeout(10*time.Second), WithTimeout(10*time.Second),
WithLogger(log.DefaultLogger),
WithEndpoint("abc"), WithEndpoint("abc"),
WithMiddleware(EmptyMiddleware()), WithMiddleware(EmptyMiddleware()),
) )

@ -6,7 +6,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/registry" "github.com/go-kratos/kratos/v2/registry"
"google.golang.org/grpc/resolver" "google.golang.org/grpc/resolver"
@ -17,13 +16,6 @@ const name = "discovery"
// Option is builder option. // Option is builder option.
type Option func(o *builder) type Option func(o *builder)
// WithLogger with builder logger.
func WithLogger(logger log.Logger) Option {
return func(b *builder) {
b.logger = logger
}
}
// WithTimeout with timeout option. // WithTimeout with timeout option.
func WithTimeout(timeout time.Duration) Option { func WithTimeout(timeout time.Duration) Option {
return func(b *builder) { return func(b *builder) {
@ -47,7 +39,6 @@ func DisableDebugLog() Option {
type builder struct { type builder struct {
discoverer registry.Discovery discoverer registry.Discovery
logger log.Logger
timeout time.Duration timeout time.Duration
insecure bool insecure bool
debugLogDisabled bool debugLogDisabled bool
@ -57,7 +48,6 @@ type builder struct {
func NewBuilder(d registry.Discovery, opts ...Option) resolver.Builder { func NewBuilder(d registry.Discovery, opts ...Option) resolver.Builder {
b := &builder{ b := &builder{
discoverer: d, discoverer: d,
logger: log.GetLogger(),
timeout: time.Second * 10, timeout: time.Second * 10,
insecure: false, insecure: false,
debugLogDisabled: false, debugLogDisabled: false,
@ -93,7 +83,6 @@ func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, opts res
cc: cc, cc: cc,
ctx: ctx, ctx: ctx,
cancel: cancel, cancel: cancel,
log: log.NewHelper(b.logger),
insecure: b.insecure, insecure: b.insecure,
debugLogDisabled: b.debugLogDisabled, debugLogDisabled: b.debugLogDisabled,
} }

@ -6,30 +6,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/registry" "github.com/go-kratos/kratos/v2/registry"
"google.golang.org/grpc/resolver" "google.golang.org/grpc/resolver"
"google.golang.org/grpc/serviceconfig" "google.golang.org/grpc/serviceconfig"
) )
type mockLogger struct {
level log.Level
key string
val string
}
func (l *mockLogger) Log(level log.Level, keyvals ...interface{}) error {
l.level = level
l.key = keyvals[0].(string)
l.val = keyvals[1].(string)
return nil
}
func TestWithLogger(t *testing.T) {
b := &builder{}
WithLogger(&mockLogger{})(b)
}
func TestWithInsecure(t *testing.T) { func TestWithInsecure(t *testing.T) {
b := &builder{} b := &builder{}
WithInsecure(true)(b) WithInsecure(true)(b)

@ -15,9 +15,8 @@ import (
) )
type discoveryResolver struct { type discoveryResolver struct {
w registry.Watcher w registry.Watcher
cc resolver.ClientConn cc resolver.ClientConn
log *log.Helper
ctx context.Context ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
@ -38,7 +37,7 @@ func (r *discoveryResolver) watch() {
if errors.Is(err, context.Canceled) { if errors.Is(err, context.Canceled) {
return return
} }
r.log.Errorf("[resolver] Failed to watch discovery endpoint: %v", err) log.Errorf("[resolver] Failed to watch discovery endpoint: %v", err)
time.Sleep(time.Second) time.Sleep(time.Second)
continue continue
} }
@ -52,7 +51,7 @@ func (r *discoveryResolver) update(ins []*registry.ServiceInstance) {
for _, in := range ins { for _, in := range ins {
endpoint, err := endpoint.ParseEndpoint(in.Endpoints, "grpc", !r.insecure) endpoint, err := endpoint.ParseEndpoint(in.Endpoints, "grpc", !r.insecure)
if err != nil { if err != nil {
r.log.Errorf("[resolver] Failed to parse discovery endpoint: %v", err) log.Errorf("[resolver] Failed to parse discovery endpoint: %v", err)
continue continue
} }
if endpoint == "" { if endpoint == "" {
@ -72,17 +71,17 @@ func (r *discoveryResolver) update(ins []*registry.ServiceInstance) {
addrs = append(addrs, addr) addrs = append(addrs, addr)
} }
if len(addrs) == 0 { if len(addrs) == 0 {
r.log.Warnf("[resolver] Zero endpoint found,refused to write, instances: %v", ins) log.Warnf("[resolver] Zero endpoint found,refused to write, instances: %v", ins)
return return
} }
err := r.cc.UpdateState(resolver.State{Addresses: addrs}) err := r.cc.UpdateState(resolver.State{Addresses: addrs})
if err != nil { if err != nil {
r.log.Errorf("[resolver] failed to update state: %s", err) log.Errorf("[resolver] failed to update state: %s", err)
} }
if !r.debugLogDisabled { if !r.debugLogDisabled {
b, _ := json.Marshal(ins) b, _ := json.Marshal(ins)
r.log.Infof("[resolver] update instances: %s", b) log.Infof("[resolver] update instances: %s", b)
} }
} }
@ -90,7 +89,7 @@ func (r *discoveryResolver) Close() {
r.cancel() r.cancel()
err := r.w.Stop() err := r.w.Stop()
if err != nil { if err != nil {
r.log.Errorf("[resolver] failed to watch top: %s", err) log.Errorf("[resolver] failed to watch top: %s", err)
} }
} }

@ -7,7 +7,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/registry" "github.com/go-kratos/kratos/v2/registry"
"google.golang.org/grpc/resolver" "google.golang.org/grpc/resolver"
) )
@ -56,7 +55,6 @@ func TestWatch(t *testing.T) {
r := &discoveryResolver{ r := &discoveryResolver{
w: &testWatch{}, w: &testWatch{},
cc: &testClientConn{te: t}, cc: &testClientConn{te: t},
log: log.NewHelper(log.GetLogger()),
ctx: ctx, ctx: ctx,
cancel: cancel, cancel: cancel,
insecure: false, insecure: false,
@ -75,7 +73,6 @@ func TestWatchError(t *testing.T) {
r := &discoveryResolver{ r := &discoveryResolver{
w: &testWatch{err: errors.New("bad")}, w: &testWatch{err: errors.New("bad")},
cc: &testClientConn{te: t}, cc: &testClientConn{te: t},
log: log.NewHelper(log.GetLogger()),
ctx: ctx, ctx: ctx,
cancel: cancel, cancel: cancel,
} }
@ -93,7 +90,6 @@ func TestWatchContextCancel(t *testing.T) {
r := &discoveryResolver{ r := &discoveryResolver{
w: &testWatch{err: context.Canceled}, w: &testWatch{err: context.Canceled},
cc: &testClientConn{te: t}, cc: &testClientConn{te: t},
log: log.NewHelper(log.GetLogger()),
ctx: ctx, ctx: ctx,
cancel: cancel, cancel: cancel,
} }

@ -54,10 +54,9 @@ func Timeout(timeout time.Duration) ServerOption {
} }
// Logger with server logger. // Logger with server logger.
// Deprecated: use global logger instead.
func Logger(logger log.Logger) ServerOption { func Logger(logger log.Logger) ServerOption {
return func(s *Server) { return func(s *Server) {}
s.log = log.NewHelper(logger)
}
} }
// Middleware with server middleware. // Middleware with server middleware.
@ -113,7 +112,6 @@ type Server struct {
address string address string
endpoint *url.URL endpoint *url.URL
timeout time.Duration timeout time.Duration
log *log.Helper
middleware []middleware.Middleware middleware []middleware.Middleware
unaryInts []grpc.UnaryServerInterceptor unaryInts []grpc.UnaryServerInterceptor
streamInts []grpc.StreamServerInterceptor streamInts []grpc.StreamServerInterceptor
@ -130,7 +128,6 @@ func NewServer(opts ...ServerOption) *Server {
address: ":0", address: ":0",
timeout: 1 * time.Second, timeout: 1 * time.Second,
health: health.NewServer(), health: health.NewServer(),
log: log.NewHelper(log.GetLogger()),
} }
for _, o := range opts { for _, o := range opts {
o(srv) o(srv)
@ -184,7 +181,7 @@ func (s *Server) Start(ctx context.Context) error {
return s.err return s.err
} }
s.baseCtx = ctx s.baseCtx = ctx
s.log.Infof("[gRPC] server listening on: %s", s.lis.Addr().String()) log.Infof("[gRPC] server listening on: %s", s.lis.Addr().String())
s.health.Resume() s.health.Resume()
return s.Serve(s.lis) return s.Serve(s.lis)
} }
@ -193,7 +190,7 @@ func (s *Server) Start(ctx context.Context) error {
func (s *Server) Stop(ctx context.Context) error { func (s *Server) Stop(ctx context.Context) error {
s.health.Shutdown() s.health.Shutdown()
s.GracefulStop() s.GracefulStop()
s.log.Info("[gRPC] server stopping") log.Info("[gRPC] server stopping")
return nil return nil
} }

@ -13,7 +13,6 @@ import (
"github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/errors"
pb "github.com/go-kratos/kratos/v2/internal/testdata/helloworld" pb "github.com/go-kratos/kratos/v2/internal/testdata/helloworld"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware" "github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport" "github.com/go-kratos/kratos/v2/transport"
@ -157,35 +156,6 @@ func TestMiddleware(t *testing.T) {
} }
} }
type mockLogger struct {
level log.Level
key string
val string
}
func (l *mockLogger) Log(level log.Level, keyvals ...interface{}) error {
l.level = level
l.key = keyvals[0].(string)
l.val = keyvals[1].(string)
return nil
}
func TestLogger(t *testing.T) {
o := &Server{}
v := &mockLogger{}
Logger(v)(o)
o.log.Log(log.LevelWarn, "foo", "bar")
if !reflect.DeepEqual("foo", v.key) {
t.Errorf("expect %s, got %s", "foo", v.key)
}
if !reflect.DeepEqual("bar", v.val) {
t.Errorf("expect %s, got %s", "bar", v.val)
}
if !reflect.DeepEqual(log.LevelWarn, v.level) {
t.Errorf("expect %s, got %s", log.LevelWarn, v.level)
}
}
func TestTLSConfig(t *testing.T) { func TestTLSConfig(t *testing.T) {
o := &Server{} o := &Server{}
v := &tls.Config{} v := &tls.Config{}

@ -44,7 +44,6 @@ type resolver struct {
target *Target target *Target
watcher registry.Watcher watcher registry.Watcher
logger *log.Helper
insecure bool insecure bool
} }
@ -57,7 +56,6 @@ func newResolver(ctx context.Context, discovery registry.Discovery, target *Targ
r := &resolver{ r := &resolver{
target: target, target: target,
watcher: watcher, watcher: watcher,
logger: log.NewHelper(log.GetLogger()),
rebalancer: rebalancer, rebalancer: rebalancer,
insecure: insecure, insecure: insecure,
} }
@ -81,15 +79,15 @@ func newResolver(ctx context.Context, discovery registry.Discovery, target *Targ
if err != nil { if err != nil {
stopErr := watcher.Stop() stopErr := watcher.Stop()
if stopErr != nil { if stopErr != nil {
r.logger.Errorf("failed to http client watch stop: %v, error: %+v", target, stopErr) log.Errorf("failed to http client watch stop: %v, error: %+v", target, stopErr)
} }
return nil, err return nil, err
} }
case <-ctx.Done(): case <-ctx.Done():
r.logger.Errorf("http client watch service %v reaching context deadline!", target) log.Errorf("http client watch service %v reaching context deadline!", target)
stopErr := watcher.Stop() stopErr := watcher.Stop()
if stopErr != nil { if stopErr != nil {
r.logger.Errorf("failed to http client watch stop: %v, error: %+v", target, stopErr) log.Errorf("failed to http client watch stop: %v, error: %+v", target, stopErr)
} }
return nil, ctx.Err() return nil, ctx.Err()
} }
@ -101,7 +99,7 @@ func newResolver(ctx context.Context, discovery registry.Discovery, target *Targ
if errors.Is(err, context.Canceled) { if errors.Is(err, context.Canceled) {
return return
} }
r.logger.Errorf("http client watch service %v got unexpected error:=%v", target, err) log.Errorf("http client watch service %v got unexpected error:=%v", target, err)
time.Sleep(time.Second) time.Sleep(time.Second)
continue continue
} }
@ -116,7 +114,7 @@ func (r *resolver) update(services []*registry.ServiceInstance) bool {
for _, ins := range services { for _, ins := range services {
ept, err := endpoint.ParseEndpoint(ins.Endpoints, "http", !r.insecure) ept, err := endpoint.ParseEndpoint(ins.Endpoints, "http", !r.insecure)
if err != nil { if err != nil {
r.logger.Errorf("Failed to parse (%v) discovery endpoint: %v error %v", r.target, ins.Endpoints, err) log.Errorf("Failed to parse (%v) discovery endpoint: %v error %v", r.target, ins.Endpoints, err)
continue continue
} }
if ept == "" { if ept == "" {
@ -125,7 +123,7 @@ func (r *resolver) update(services []*registry.ServiceInstance) bool {
nodes = append(nodes, selector.NewNode("http", ept, ins)) nodes = append(nodes, selector.NewNode("http", ept, ins))
} }
if len(nodes) == 0 { if len(nodes) == 0 {
r.logger.Warnf("[http resolver]Zero endpoint found,refused to write,set: %s ins: %v", r.target.Endpoint, nodes) log.Warnf("[http resolver]Zero endpoint found,refused to write,set: %s ins: %v", r.target.Endpoint, nodes)
return false return false
} }
r.rebalancer.Apply(nodes) r.rebalancer.Apply(nodes)

@ -49,10 +49,9 @@ func Timeout(timeout time.Duration) ServerOption {
} }
// Logger with server logger. // Logger with server logger.
// Deprecated: use global logger instead.
func Logger(logger log.Logger) ServerOption { func Logger(logger log.Logger) ServerOption {
return func(s *Server) { return func(s *Server) {}
s.log = log.NewHelper(logger)
}
} }
// Middleware with service middleware option. // Middleware with service middleware option.
@ -130,7 +129,6 @@ type Server struct {
ene EncodeErrorFunc ene EncodeErrorFunc
strictSlash bool strictSlash bool
router *mux.Router router *mux.Router
log *log.Helper
} }
// NewServer creates an HTTP server by options. // NewServer creates an HTTP server by options.
@ -143,7 +141,6 @@ func NewServer(opts ...ServerOption) *Server {
enc: DefaultResponseEncoder, enc: DefaultResponseEncoder,
ene: DefaultErrorEncoder, ene: DefaultErrorEncoder,
strictSlash: true, strictSlash: true,
log: log.NewHelper(log.GetLogger()),
} }
for _, o := range opts { for _, o := range opts {
o(srv) o(srv)
@ -243,7 +240,7 @@ func (s *Server) Start(ctx context.Context) error {
s.BaseContext = func(net.Listener) context.Context { s.BaseContext = func(net.Listener) context.Context {
return ctx return ctx
} }
s.log.Infof("[HTTP] server listening on: %s", s.lis.Addr().String()) log.Infof("[HTTP] server listening on: %s", s.lis.Addr().String())
var err error var err error
if s.tlsConf != nil { if s.tlsConf != nil {
err = s.ServeTLS(s.lis, "", "") err = s.ServeTLS(s.lis, "", "")
@ -258,7 +255,7 @@ func (s *Server) Start(ctx context.Context) error {
// Stop stop the HTTP server. // Stop stop the HTTP server.
func (s *Server) Stop(ctx context.Context) error { func (s *Server) Stop(ctx context.Context) error {
s.log.Info("[HTTP] server stopping") log.Info("[HTTP] server stopping")
return s.Shutdown(ctx) return s.Shutdown(ctx)
} }

Loading…
Cancel
Save