prefixLogger.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. *
  3. * Copyright 2020 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpclog
  19. import (
  20. "fmt"
  21. )
  22. // PrefixLogger does logging with a prefix.
  23. //
  24. // Logging method on a nil logs without any prefix.
  25. type PrefixLogger struct {
  26. logger DepthLoggerV2
  27. prefix string
  28. }
  29. // Infof does info logging.
  30. func (pl *PrefixLogger) Infof(format string, args ...interface{}) {
  31. if pl != nil {
  32. // Handle nil, so the tests can pass in a nil logger.
  33. format = pl.prefix + format
  34. pl.logger.InfoDepth(1, fmt.Sprintf(format, args...))
  35. return
  36. }
  37. InfoDepth(1, fmt.Sprintf(format, args...))
  38. }
  39. // Warningf does warning logging.
  40. func (pl *PrefixLogger) Warningf(format string, args ...interface{}) {
  41. if pl != nil {
  42. format = pl.prefix + format
  43. pl.logger.WarningDepth(1, fmt.Sprintf(format, args...))
  44. return
  45. }
  46. WarningDepth(1, fmt.Sprintf(format, args...))
  47. }
  48. // Errorf does error logging.
  49. func (pl *PrefixLogger) Errorf(format string, args ...interface{}) {
  50. if pl != nil {
  51. format = pl.prefix + format
  52. pl.logger.ErrorDepth(1, fmt.Sprintf(format, args...))
  53. return
  54. }
  55. ErrorDepth(1, fmt.Sprintf(format, args...))
  56. }
  57. // Debugf does info logging at verbose level 2.
  58. func (pl *PrefixLogger) Debugf(format string, args ...interface{}) {
  59. if !Logger.V(2) {
  60. return
  61. }
  62. if pl != nil {
  63. // Handle nil, so the tests can pass in a nil logger.
  64. format = pl.prefix + format
  65. pl.logger.InfoDepth(1, fmt.Sprintf(format, args...))
  66. return
  67. }
  68. InfoDepth(1, fmt.Sprintf(format, args...))
  69. }
  70. // NewPrefixLogger creates a prefix logger with the given prefix.
  71. func NewPrefixLogger(logger DepthLoggerV2, prefix string) *PrefixLogger {
  72. return &PrefixLogger{logger: logger, prefix: prefix}
  73. }