loggerv2.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. *
  3. * Copyright 2017 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. "encoding/json"
  21. "fmt"
  22. "io"
  23. "log"
  24. "os"
  25. "strconv"
  26. "strings"
  27. "google.golang.org/grpc/internal/grpclog"
  28. )
  29. // LoggerV2 does underlying logging work for grpclog.
  30. type LoggerV2 interface {
  31. // Info logs to INFO log. Arguments are handled in the manner of fmt.Print.
  32. Info(args ...interface{})
  33. // Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println.
  34. Infoln(args ...interface{})
  35. // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
  36. Infof(format string, args ...interface{})
  37. // Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print.
  38. Warning(args ...interface{})
  39. // Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println.
  40. Warningln(args ...interface{})
  41. // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
  42. Warningf(format string, args ...interface{})
  43. // Error logs to ERROR log. Arguments are handled in the manner of fmt.Print.
  44. Error(args ...interface{})
  45. // Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
  46. Errorln(args ...interface{})
  47. // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
  48. Errorf(format string, args ...interface{})
  49. // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print.
  50. // gRPC ensures that all Fatal logs will exit with os.Exit(1).
  51. // Implementations may also call os.Exit() with a non-zero exit code.
  52. Fatal(args ...interface{})
  53. // Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
  54. // gRPC ensures that all Fatal logs will exit with os.Exit(1).
  55. // Implementations may also call os.Exit() with a non-zero exit code.
  56. Fatalln(args ...interface{})
  57. // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
  58. // gRPC ensures that all Fatal logs will exit with os.Exit(1).
  59. // Implementations may also call os.Exit() with a non-zero exit code.
  60. Fatalf(format string, args ...interface{})
  61. // V reports whether verbosity level l is at least the requested verbose level.
  62. V(l int) bool
  63. }
  64. // SetLoggerV2 sets logger that is used in grpc to a V2 logger.
  65. // Not mutex-protected, should be called before any gRPC functions.
  66. func SetLoggerV2(l LoggerV2) {
  67. if _, ok := l.(*componentData); ok {
  68. panic("cannot use component logger as grpclog logger")
  69. }
  70. grpclog.Logger = l
  71. grpclog.DepthLogger, _ = l.(grpclog.DepthLoggerV2)
  72. }
  73. const (
  74. // infoLog indicates Info severity.
  75. infoLog int = iota
  76. // warningLog indicates Warning severity.
  77. warningLog
  78. // errorLog indicates Error severity.
  79. errorLog
  80. // fatalLog indicates Fatal severity.
  81. fatalLog
  82. )
  83. // severityName contains the string representation of each severity.
  84. var severityName = []string{
  85. infoLog: "INFO",
  86. warningLog: "WARNING",
  87. errorLog: "ERROR",
  88. fatalLog: "FATAL",
  89. }
  90. // loggerT is the default logger used by grpclog.
  91. type loggerT struct {
  92. m []*log.Logger
  93. v int
  94. jsonFormat bool
  95. }
  96. // NewLoggerV2 creates a loggerV2 with the provided writers.
  97. // Fatal logs will be written to errorW, warningW, infoW, followed by exit(1).
  98. // Error logs will be written to errorW, warningW and infoW.
  99. // Warning logs will be written to warningW and infoW.
  100. // Info logs will be written to infoW.
  101. func NewLoggerV2(infoW, warningW, errorW io.Writer) LoggerV2 {
  102. return newLoggerV2WithConfig(infoW, warningW, errorW, loggerV2Config{})
  103. }
  104. // NewLoggerV2WithVerbosity creates a loggerV2 with the provided writers and
  105. // verbosity level.
  106. func NewLoggerV2WithVerbosity(infoW, warningW, errorW io.Writer, v int) LoggerV2 {
  107. return newLoggerV2WithConfig(infoW, warningW, errorW, loggerV2Config{verbose: v})
  108. }
  109. type loggerV2Config struct {
  110. verbose int
  111. jsonFormat bool
  112. }
  113. func newLoggerV2WithConfig(infoW, warningW, errorW io.Writer, c loggerV2Config) LoggerV2 {
  114. var m []*log.Logger
  115. flag := log.LstdFlags
  116. if c.jsonFormat {
  117. flag = 0
  118. }
  119. m = append(m, log.New(infoW, "", flag))
  120. m = append(m, log.New(io.MultiWriter(infoW, warningW), "", flag))
  121. ew := io.MultiWriter(infoW, warningW, errorW) // ew will be used for error and fatal.
  122. m = append(m, log.New(ew, "", flag))
  123. m = append(m, log.New(ew, "", flag))
  124. return &loggerT{m: m, v: c.verbose, jsonFormat: c.jsonFormat}
  125. }
  126. // newLoggerV2 creates a loggerV2 to be used as default logger.
  127. // All logs are written to stderr.
  128. func newLoggerV2() LoggerV2 {
  129. errorW := io.Discard
  130. warningW := io.Discard
  131. infoW := io.Discard
  132. logLevel := os.Getenv("GRPC_GO_LOG_SEVERITY_LEVEL")
  133. switch logLevel {
  134. case "", "ERROR", "error": // If env is unset, set level to ERROR.
  135. errorW = os.Stderr
  136. case "WARNING", "warning":
  137. warningW = os.Stderr
  138. case "INFO", "info":
  139. infoW = os.Stderr
  140. }
  141. var v int
  142. vLevel := os.Getenv("GRPC_GO_LOG_VERBOSITY_LEVEL")
  143. if vl, err := strconv.Atoi(vLevel); err == nil {
  144. v = vl
  145. }
  146. jsonFormat := strings.EqualFold(os.Getenv("GRPC_GO_LOG_FORMATTER"), "json")
  147. return newLoggerV2WithConfig(infoW, warningW, errorW, loggerV2Config{
  148. verbose: v,
  149. jsonFormat: jsonFormat,
  150. })
  151. }
  152. func (g *loggerT) output(severity int, s string) {
  153. sevStr := severityName[severity]
  154. if !g.jsonFormat {
  155. g.m[severity].Output(2, fmt.Sprintf("%v: %v", sevStr, s))
  156. return
  157. }
  158. // TODO: we can also include the logging component, but that needs more
  159. // (API) changes.
  160. b, _ := json.Marshal(map[string]string{
  161. "severity": sevStr,
  162. "message": s,
  163. })
  164. g.m[severity].Output(2, string(b))
  165. }
  166. func (g *loggerT) Info(args ...interface{}) {
  167. g.output(infoLog, fmt.Sprint(args...))
  168. }
  169. func (g *loggerT) Infoln(args ...interface{}) {
  170. g.output(infoLog, fmt.Sprintln(args...))
  171. }
  172. func (g *loggerT) Infof(format string, args ...interface{}) {
  173. g.output(infoLog, fmt.Sprintf(format, args...))
  174. }
  175. func (g *loggerT) Warning(args ...interface{}) {
  176. g.output(warningLog, fmt.Sprint(args...))
  177. }
  178. func (g *loggerT) Warningln(args ...interface{}) {
  179. g.output(warningLog, fmt.Sprintln(args...))
  180. }
  181. func (g *loggerT) Warningf(format string, args ...interface{}) {
  182. g.output(warningLog, fmt.Sprintf(format, args...))
  183. }
  184. func (g *loggerT) Error(args ...interface{}) {
  185. g.output(errorLog, fmt.Sprint(args...))
  186. }
  187. func (g *loggerT) Errorln(args ...interface{}) {
  188. g.output(errorLog, fmt.Sprintln(args...))
  189. }
  190. func (g *loggerT) Errorf(format string, args ...interface{}) {
  191. g.output(errorLog, fmt.Sprintf(format, args...))
  192. }
  193. func (g *loggerT) Fatal(args ...interface{}) {
  194. g.output(fatalLog, fmt.Sprint(args...))
  195. os.Exit(1)
  196. }
  197. func (g *loggerT) Fatalln(args ...interface{}) {
  198. g.output(fatalLog, fmt.Sprintln(args...))
  199. os.Exit(1)
  200. }
  201. func (g *loggerT) Fatalf(format string, args ...interface{}) {
  202. g.output(fatalLog, fmt.Sprintf(format, args...))
  203. os.Exit(1)
  204. }
  205. func (g *loggerT) V(l int) bool {
  206. return l <= g.v
  207. }
  208. // DepthLoggerV2 logs at a specified call frame. If a LoggerV2 also implements
  209. // DepthLoggerV2, the below functions will be called with the appropriate stack
  210. // depth set for trivial functions the logger may ignore.
  211. //
  212. // # Experimental
  213. //
  214. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  215. // later release.
  216. type DepthLoggerV2 interface {
  217. LoggerV2
  218. // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Println.
  219. InfoDepth(depth int, args ...interface{})
  220. // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Println.
  221. WarningDepth(depth int, args ...interface{})
  222. // ErrorDepth logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Println.
  223. ErrorDepth(depth int, args ...interface{})
  224. // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Println.
  225. FatalDepth(depth int, args ...interface{})
  226. }