logger.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package clientv3
  15. import (
  16. "log"
  17. "os"
  18. "go.etcd.io/etcd/client/pkg/v3/logutil"
  19. "go.uber.org/zap/zapcore"
  20. "go.uber.org/zap/zapgrpc"
  21. "google.golang.org/grpc/grpclog"
  22. )
  23. func init() {
  24. // We override grpc logger only when the environment variable is set
  25. // in order to not interfere by default with user's code or other libraries.
  26. if os.Getenv("ETCD_CLIENT_DEBUG") != "" {
  27. lg, err := logutil.CreateDefaultZapLogger(etcdClientDebugLevel())
  28. if err != nil {
  29. panic(err)
  30. }
  31. lg = lg.Named("etcd-client")
  32. grpclog.SetLoggerV2(zapgrpc.NewLogger(lg))
  33. }
  34. }
  35. // SetLogger sets grpc logger.
  36. //
  37. // Deprecated: use grpclog.SetLoggerV2 directly or grpc_zap.ReplaceGrpcLoggerV2.
  38. func SetLogger(l grpclog.LoggerV2) {
  39. grpclog.SetLoggerV2(l)
  40. }
  41. // etcdClientDebugLevel translates ETCD_CLIENT_DEBUG into zap log level.
  42. func etcdClientDebugLevel() zapcore.Level {
  43. envLevel := os.Getenv("ETCD_CLIENT_DEBUG")
  44. if envLevel == "" || envLevel == "true" {
  45. return zapcore.InfoLevel
  46. }
  47. var l zapcore.Level
  48. if err := l.Set(envLevel); err != nil {
  49. log.Printf("Invalid value for environment variable 'ETCD_CLIENT_DEBUG'. Using default level: 'info'")
  50. return zapcore.InfoLevel
  51. }
  52. return l
  53. }