glog_flags.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Go support for leveled logs, analogous to https://github.com/google/glog.
  2. //
  3. // Copyright 2023 Google Inc. All Rights Reserved.
  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. package glog
  17. import (
  18. "bytes"
  19. "errors"
  20. "flag"
  21. "fmt"
  22. "path/filepath"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "sync/atomic"
  28. "github.com/golang/glog/internal/logsink"
  29. )
  30. // modulePat contains a filter for the -vmodule flag.
  31. // It holds a verbosity level and a file pattern to match.
  32. type modulePat struct {
  33. pattern string
  34. literal bool // The pattern is a literal string
  35. full bool // The pattern wants to match the full path
  36. level Level
  37. }
  38. // match reports whether the file matches the pattern. It uses a string
  39. // comparison if the pattern contains no metacharacters.
  40. func (m *modulePat) match(full, file string) bool {
  41. if m.literal {
  42. if m.full {
  43. return full == m.pattern
  44. }
  45. return file == m.pattern
  46. }
  47. if m.full {
  48. match, _ := filepath.Match(m.pattern, full)
  49. return match
  50. }
  51. match, _ := filepath.Match(m.pattern, file)
  52. return match
  53. }
  54. // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters
  55. // that require filepath.Match to be called to match the pattern.
  56. func isLiteral(pattern string) bool {
  57. return !strings.ContainsAny(pattern, `\*?[]`)
  58. }
  59. // isFull reports whether the pattern matches the full file path, that is,
  60. // whether it contains /.
  61. func isFull(pattern string) bool {
  62. return strings.ContainsRune(pattern, '/')
  63. }
  64. // verboseFlags represents the setting of the -v and -vmodule flags.
  65. type verboseFlags struct {
  66. // moduleLevelCache is a sync.Map storing the -vmodule Level for each V()
  67. // call site, identified by PC. If there is no matching -vmodule filter,
  68. // the cached value is exactly v. moduleLevelCache is replaced with a new
  69. // Map whenever the -vmodule or -v flag changes state.
  70. moduleLevelCache atomic.Value
  71. // mu guards all fields below.
  72. mu sync.Mutex
  73. // v stores the value of the -v flag. It may be read safely using
  74. // sync.LoadInt32, but is only modified under mu.
  75. v Level
  76. // module stores the parsed -vmodule flag.
  77. module []modulePat
  78. // moduleLength caches len(module). If greater than zero, it
  79. // means vmodule is enabled. It may be read safely using sync.LoadInt32, but
  80. // is only modified under mu.
  81. moduleLength int32
  82. }
  83. // NOTE: For compatibility with the open-sourced v1 version of this
  84. // package (github.com/golang/glog) we need to retain that flag.Level
  85. // implements the flag.Value interface. See also go/log-vs-glog.
  86. // String is part of the flag.Value interface.
  87. func (l *Level) String() string {
  88. return strconv.FormatInt(int64(l.Get().(Level)), 10)
  89. }
  90. // Get is part of the flag.Value interface.
  91. func (l *Level) Get() any {
  92. if l == &vflags.v {
  93. // l is the value registered for the -v flag.
  94. return Level(atomic.LoadInt32((*int32)(l)))
  95. }
  96. return *l
  97. }
  98. // Set is part of the flag.Value interface.
  99. func (l *Level) Set(value string) error {
  100. v, err := strconv.Atoi(value)
  101. if err != nil {
  102. return err
  103. }
  104. if l == &vflags.v {
  105. // l is the value registered for the -v flag.
  106. vflags.mu.Lock()
  107. defer vflags.mu.Unlock()
  108. vflags.moduleLevelCache.Store(&sync.Map{})
  109. atomic.StoreInt32((*int32)(l), int32(v))
  110. return nil
  111. }
  112. *l = Level(v)
  113. return nil
  114. }
  115. // vModuleFlag is the flag.Value for the --vmodule flag.
  116. type vModuleFlag struct{ *verboseFlags }
  117. func (f vModuleFlag) String() string {
  118. f.mu.Lock()
  119. defer f.mu.Unlock()
  120. var b bytes.Buffer
  121. for i, f := range f.module {
  122. if i > 0 {
  123. b.WriteRune(',')
  124. }
  125. fmt.Fprintf(&b, "%s=%d", f.pattern, f.level)
  126. }
  127. return b.String()
  128. }
  129. // Get returns nil for this flag type since the struct is not exported.
  130. func (f vModuleFlag) Get() any { return nil }
  131. var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N")
  132. // Syntax: -vmodule=recordio=2,foo/bar/baz=1,gfs*=3
  133. func (f vModuleFlag) Set(value string) error {
  134. var filter []modulePat
  135. for _, pat := range strings.Split(value, ",") {
  136. if len(pat) == 0 {
  137. // Empty strings such as from a trailing comma can be ignored.
  138. continue
  139. }
  140. patLev := strings.Split(pat, "=")
  141. if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {
  142. return errVmoduleSyntax
  143. }
  144. pattern := patLev[0]
  145. v, err := strconv.Atoi(patLev[1])
  146. if err != nil {
  147. return errors.New("syntax error: expect comma-separated list of filename=N")
  148. }
  149. // TODO: check syntax of filter?
  150. filter = append(filter, modulePat{pattern, isLiteral(pattern), isFull(pattern), Level(v)})
  151. }
  152. f.mu.Lock()
  153. defer f.mu.Unlock()
  154. f.module = filter
  155. atomic.StoreInt32((*int32)(&f.moduleLength), int32(len(f.module)))
  156. f.moduleLevelCache.Store(&sync.Map{})
  157. return nil
  158. }
  159. func (f *verboseFlags) levelForPC(pc uintptr) Level {
  160. if level, ok := f.moduleLevelCache.Load().(*sync.Map).Load(pc); ok {
  161. return level.(Level)
  162. }
  163. f.mu.Lock()
  164. defer f.mu.Unlock()
  165. level := Level(f.v)
  166. fn := runtime.FuncForPC(pc)
  167. file, _ := fn.FileLine(pc)
  168. // The file is something like /a/b/c/d.go. We want just the d for
  169. // regular matches, /a/b/c/d for full matches.
  170. if strings.HasSuffix(file, ".go") {
  171. file = file[:len(file)-3]
  172. }
  173. full := file
  174. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  175. file = file[slash+1:]
  176. }
  177. for _, filter := range f.module {
  178. if filter.match(full, file) {
  179. level = filter.level
  180. break // Use the first matching level.
  181. }
  182. }
  183. f.moduleLevelCache.Load().(*sync.Map).Store(pc, level)
  184. return level
  185. }
  186. func (f *verboseFlags) enabled(callerDepth int, level Level) bool {
  187. if atomic.LoadInt32(&f.moduleLength) == 0 {
  188. // No vmodule values specified, so compare against v level.
  189. return Level(atomic.LoadInt32((*int32)(&f.v))) >= level
  190. }
  191. pcs := [1]uintptr{}
  192. if runtime.Callers(callerDepth+2, pcs[:]) < 1 {
  193. return false
  194. }
  195. frame, _ := runtime.CallersFrames(pcs[:]).Next()
  196. return f.levelForPC(frame.Entry) >= level
  197. }
  198. // traceLocation represents an entry in the -log_backtrace_at flag.
  199. type traceLocation struct {
  200. file string
  201. line int
  202. }
  203. var errTraceSyntax = errors.New("syntax error: expect file.go:234")
  204. func parseTraceLocation(value string) (traceLocation, error) {
  205. fields := strings.Split(value, ":")
  206. if len(fields) != 2 {
  207. return traceLocation{}, errTraceSyntax
  208. }
  209. file, lineStr := fields[0], fields[1]
  210. if !strings.Contains(file, ".") {
  211. return traceLocation{}, errTraceSyntax
  212. }
  213. line, err := strconv.Atoi(lineStr)
  214. if err != nil {
  215. return traceLocation{}, errTraceSyntax
  216. }
  217. if line < 0 {
  218. return traceLocation{}, errors.New("negative value for line")
  219. }
  220. return traceLocation{file, line}, nil
  221. }
  222. // match reports whether the specified file and line matches the trace location.
  223. // The argument file name is the full path, not the basename specified in the flag.
  224. func (t traceLocation) match(file string, line int) bool {
  225. if t.line != line {
  226. return false
  227. }
  228. if i := strings.LastIndex(file, "/"); i >= 0 {
  229. file = file[i+1:]
  230. }
  231. return t.file == file
  232. }
  233. func (t traceLocation) String() string {
  234. return fmt.Sprintf("%s:%d", t.file, t.line)
  235. }
  236. // traceLocations represents the -log_backtrace_at flag.
  237. // Syntax: -log_backtrace_at=recordio.go:234,sstable.go:456
  238. // Note that unlike vmodule the file extension is included here.
  239. type traceLocations struct {
  240. mu sync.Mutex
  241. locsLen int32 // Safe for atomic read without mu.
  242. locs []traceLocation
  243. }
  244. func (t *traceLocations) String() string {
  245. t.mu.Lock()
  246. defer t.mu.Unlock()
  247. var buf bytes.Buffer
  248. for i, tl := range t.locs {
  249. if i > 0 {
  250. buf.WriteString(",")
  251. }
  252. buf.WriteString(tl.String())
  253. }
  254. return buf.String()
  255. }
  256. // Get always returns nil for this flag type since the struct is not exported
  257. func (t *traceLocations) Get() any { return nil }
  258. func (t *traceLocations) Set(value string) error {
  259. var locs []traceLocation
  260. for _, s := range strings.Split(value, ",") {
  261. if s == "" {
  262. continue
  263. }
  264. loc, err := parseTraceLocation(s)
  265. if err != nil {
  266. return err
  267. }
  268. locs = append(locs, loc)
  269. }
  270. t.mu.Lock()
  271. defer t.mu.Unlock()
  272. atomic.StoreInt32(&t.locsLen, int32(len(locs)))
  273. t.locs = locs
  274. return nil
  275. }
  276. func (t *traceLocations) match(file string, line int) bool {
  277. if atomic.LoadInt32(&t.locsLen) == 0 {
  278. return false
  279. }
  280. t.mu.Lock()
  281. defer t.mu.Unlock()
  282. for _, tl := range t.locs {
  283. if tl.match(file, line) {
  284. return true
  285. }
  286. }
  287. return false
  288. }
  289. // severityFlag is an atomic flag.Value implementation for logsink.Severity.
  290. type severityFlag int32
  291. func (s *severityFlag) get() logsink.Severity {
  292. return logsink.Severity(atomic.LoadInt32((*int32)(s)))
  293. }
  294. func (s *severityFlag) String() string { return strconv.FormatInt(int64(*s), 10) }
  295. func (s *severityFlag) Get() any { return s.get() }
  296. func (s *severityFlag) Set(value string) error {
  297. threshold, err := logsink.ParseSeverity(value)
  298. if err != nil {
  299. // Not a severity name. Try a raw number.
  300. v, err := strconv.Atoi(value)
  301. if err != nil {
  302. return err
  303. }
  304. threshold = logsink.Severity(v)
  305. if threshold < logsink.Info || threshold > logsink.Fatal {
  306. return fmt.Errorf("Severity %d out of range (min %d, max %d).", v, logsink.Info, logsink.Fatal)
  307. }
  308. }
  309. atomic.StoreInt32((*int32)(s), int32(threshold))
  310. return nil
  311. }
  312. var (
  313. vflags verboseFlags // The -v and -vmodule flags.
  314. logBacktraceAt traceLocations // The -log_backtrace_at flag.
  315. // Boolean flags. Not handled atomically because the flag.Value interface
  316. // does not let us avoid the =true, and that shorthand is necessary for
  317. // compatibility. TODO: does this matter enough to fix? Seems unlikely.
  318. toStderr bool // The -logtostderr flag.
  319. alsoToStderr bool // The -alsologtostderr flag.
  320. stderrThreshold severityFlag // The -stderrthreshold flag.
  321. )
  322. // verboseEnabled returns whether the caller at the given depth should emit
  323. // verbose logs at the given level, with depth 0 identifying the caller of
  324. // verboseEnabled.
  325. func verboseEnabled(callerDepth int, level Level) bool {
  326. return vflags.enabled(callerDepth+1, level)
  327. }
  328. // backtraceAt returns whether the logging call at the given function and line
  329. // should also emit a backtrace of the current call stack.
  330. func backtraceAt(file string, line int) bool {
  331. return logBacktraceAt.match(file, line)
  332. }
  333. func init() {
  334. vflags.moduleLevelCache.Store(&sync.Map{})
  335. flag.Var(&vflags.v, "v", "log level for V logs")
  336. flag.Var(vModuleFlag{&vflags}, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
  337. flag.Var(&logBacktraceAt, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
  338. stderrThreshold = severityFlag(logsink.Error)
  339. flag.BoolVar(&toStderr, "logtostderr", false, "log to standard error instead of files")
  340. flag.BoolVar(&alsoToStderr, "alsologtostderr", false, "log to standard error as well as files")
  341. flag.Var(&stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
  342. }