logger.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. "io/ioutil"
  17. "log"
  18. "sync"
  19. "google.golang.org/grpc/grpclog"
  20. )
  21. // Logger is the logger used by client library.
  22. // It implements grpclog.Logger interface.
  23. type Logger grpclog.Logger
  24. var (
  25. logger settableLogger
  26. )
  27. type settableLogger struct {
  28. l grpclog.Logger
  29. mu sync.RWMutex
  30. }
  31. func init() {
  32. // disable client side logs by default
  33. logger.mu.Lock()
  34. logger.l = log.New(ioutil.Discard, "", 0)
  35. // logger has to override the grpclog at initialization so that
  36. // any changes to the grpclog go through logger with locking
  37. // instead of through SetLogger
  38. //
  39. // now updates only happen through settableLogger.set
  40. grpclog.SetLogger(&logger)
  41. logger.mu.Unlock()
  42. }
  43. // SetLogger sets client-side Logger. By default, logs are disabled.
  44. func SetLogger(l Logger) {
  45. logger.set(l)
  46. }
  47. // GetLogger returns the current logger.
  48. func GetLogger() Logger {
  49. return logger.get()
  50. }
  51. func (s *settableLogger) set(l Logger) {
  52. s.mu.Lock()
  53. logger.l = l
  54. s.mu.Unlock()
  55. }
  56. func (s *settableLogger) get() Logger {
  57. s.mu.RLock()
  58. l := logger.l
  59. s.mu.RUnlock()
  60. return l
  61. }
  62. // implement the grpclog.Logger interface
  63. func (s *settableLogger) Fatal(args ...interface{}) { s.get().Fatal(args...) }
  64. func (s *settableLogger) Fatalf(format string, args ...interface{}) { s.get().Fatalf(format, args...) }
  65. func (s *settableLogger) Fatalln(args ...interface{}) { s.get().Fatalln(args...) }
  66. func (s *settableLogger) Print(args ...interface{}) { s.get().Print(args...) }
  67. func (s *settableLogger) Printf(format string, args ...interface{}) { s.get().Printf(format, args...) }
  68. func (s *settableLogger) Println(args ...interface{}) { s.get().Println(args...) }