klog.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/
  2. //
  3. // Copyright 2013 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 klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
  17. // It provides functions Info, Warning, Error, Fatal, plus formatting variants such as
  18. // Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
  19. //
  20. // Basic examples:
  21. //
  22. // klog.Info("Prepare to repel boarders")
  23. //
  24. // klog.Fatalf("Initialization failed: %s", err)
  25. //
  26. // See the documentation for the V function for an explanation of these examples:
  27. //
  28. // if klog.V(2) {
  29. // klog.Info("Starting transaction...")
  30. // }
  31. //
  32. // klog.V(2).Infoln("Processed", nItems, "elements")
  33. //
  34. // Log output is buffered and written periodically using Flush. Programs
  35. // should call Flush before exiting to guarantee all log output is written.
  36. //
  37. // By default, all log statements write to standard error.
  38. // This package provides several flags that modify this behavior.
  39. // As a result, flag.Parse must be called before any logging is done.
  40. //
  41. // -logtostderr=true
  42. // Logs are written to standard error instead of to files.
  43. // -alsologtostderr=false
  44. // Logs are written to standard error as well as to files.
  45. // -stderrthreshold=ERROR
  46. // Log events at or above this severity are logged to standard
  47. // error as well as to files.
  48. // -log_dir=""
  49. // Log files will be written to this directory instead of the
  50. // default temporary directory.
  51. //
  52. // Other flags provide aids to debugging.
  53. //
  54. // -log_backtrace_at=""
  55. // When set to a file and line number holding a logging statement,
  56. // such as
  57. // -log_backtrace_at=gopherflakes.go:234
  58. // a stack trace will be written to the Info log whenever execution
  59. // hits that statement. (Unlike with -vmodule, the ".go" must be
  60. // present.)
  61. // -v=0
  62. // Enable V-leveled logging at the specified level.
  63. // -vmodule=""
  64. // The syntax of the argument is a comma-separated list of pattern=N,
  65. // where pattern is a literal file name (minus the ".go" suffix) or
  66. // "glob" pattern and N is a V level. For instance,
  67. // -vmodule=gopher*=3
  68. // sets the V level to 3 in all Go files whose names begin "gopher".
  69. //
  70. package klog
  71. import (
  72. "bufio"
  73. "bytes"
  74. "errors"
  75. "flag"
  76. "fmt"
  77. "io"
  78. stdLog "log"
  79. "math"
  80. "os"
  81. "path/filepath"
  82. "runtime"
  83. "strconv"
  84. "strings"
  85. "sync"
  86. "sync/atomic"
  87. "time"
  88. "github.com/go-logr/logr"
  89. )
  90. // severity identifies the sort of log: info, warning etc. It also implements
  91. // the flag.Value interface. The -stderrthreshold flag is of type severity and
  92. // should be modified only through the flag.Value interface. The values match
  93. // the corresponding constants in C++.
  94. type severity int32 // sync/atomic int32
  95. // These constants identify the log levels in order of increasing severity.
  96. // A message written to a high-severity log file is also written to each
  97. // lower-severity log file.
  98. const (
  99. infoLog severity = iota
  100. warningLog
  101. errorLog
  102. fatalLog
  103. numSeverity = 4
  104. )
  105. const severityChar = "IWEF"
  106. var severityName = []string{
  107. infoLog: "INFO",
  108. warningLog: "WARNING",
  109. errorLog: "ERROR",
  110. fatalLog: "FATAL",
  111. }
  112. // get returns the value of the severity.
  113. func (s *severity) get() severity {
  114. return severity(atomic.LoadInt32((*int32)(s)))
  115. }
  116. // set sets the value of the severity.
  117. func (s *severity) set(val severity) {
  118. atomic.StoreInt32((*int32)(s), int32(val))
  119. }
  120. // String is part of the flag.Value interface.
  121. func (s *severity) String() string {
  122. return strconv.FormatInt(int64(*s), 10)
  123. }
  124. // Get is part of the flag.Getter interface.
  125. func (s *severity) Get() interface{} {
  126. return *s
  127. }
  128. // Set is part of the flag.Value interface.
  129. func (s *severity) Set(value string) error {
  130. var threshold severity
  131. // Is it a known name?
  132. if v, ok := severityByName(value); ok {
  133. threshold = v
  134. } else {
  135. v, err := strconv.ParseInt(value, 10, 32)
  136. if err != nil {
  137. return err
  138. }
  139. threshold = severity(v)
  140. }
  141. logging.stderrThreshold.set(threshold)
  142. return nil
  143. }
  144. func severityByName(s string) (severity, bool) {
  145. s = strings.ToUpper(s)
  146. for i, name := range severityName {
  147. if name == s {
  148. return severity(i), true
  149. }
  150. }
  151. return 0, false
  152. }
  153. // OutputStats tracks the number of output lines and bytes written.
  154. type OutputStats struct {
  155. lines int64
  156. bytes int64
  157. }
  158. // Lines returns the number of lines written.
  159. func (s *OutputStats) Lines() int64 {
  160. return atomic.LoadInt64(&s.lines)
  161. }
  162. // Bytes returns the number of bytes written.
  163. func (s *OutputStats) Bytes() int64 {
  164. return atomic.LoadInt64(&s.bytes)
  165. }
  166. // Stats tracks the number of lines of output and number of bytes
  167. // per severity level. Values must be read with atomic.LoadInt64.
  168. var Stats struct {
  169. Info, Warning, Error OutputStats
  170. }
  171. var severityStats = [numSeverity]*OutputStats{
  172. infoLog: &Stats.Info,
  173. warningLog: &Stats.Warning,
  174. errorLog: &Stats.Error,
  175. }
  176. // Level is exported because it appears in the arguments to V and is
  177. // the type of the v flag, which can be set programmatically.
  178. // It's a distinct type because we want to discriminate it from logType.
  179. // Variables of type level are only changed under logging.mu.
  180. // The -v flag is read only with atomic ops, so the state of the logging
  181. // module is consistent.
  182. // Level is treated as a sync/atomic int32.
  183. // Level specifies a level of verbosity for V logs. *Level implements
  184. // flag.Value; the -v flag is of type Level and should be modified
  185. // only through the flag.Value interface.
  186. type Level int32
  187. // get returns the value of the Level.
  188. func (l *Level) get() Level {
  189. return Level(atomic.LoadInt32((*int32)(l)))
  190. }
  191. // set sets the value of the Level.
  192. func (l *Level) set(val Level) {
  193. atomic.StoreInt32((*int32)(l), int32(val))
  194. }
  195. // String is part of the flag.Value interface.
  196. func (l *Level) String() string {
  197. return strconv.FormatInt(int64(*l), 10)
  198. }
  199. // Get is part of the flag.Getter interface.
  200. func (l *Level) Get() interface{} {
  201. return *l
  202. }
  203. // Set is part of the flag.Value interface.
  204. func (l *Level) Set(value string) error {
  205. v, err := strconv.ParseInt(value, 10, 32)
  206. if err != nil {
  207. return err
  208. }
  209. logging.mu.Lock()
  210. defer logging.mu.Unlock()
  211. logging.setVState(Level(v), logging.vmodule.filter, false)
  212. return nil
  213. }
  214. // moduleSpec represents the setting of the -vmodule flag.
  215. type moduleSpec struct {
  216. filter []modulePat
  217. }
  218. // modulePat contains a filter for the -vmodule flag.
  219. // It holds a verbosity level and a file pattern to match.
  220. type modulePat struct {
  221. pattern string
  222. literal bool // The pattern is a literal string
  223. level Level
  224. }
  225. // match reports whether the file matches the pattern. It uses a string
  226. // comparison if the pattern contains no metacharacters.
  227. func (m *modulePat) match(file string) bool {
  228. if m.literal {
  229. return file == m.pattern
  230. }
  231. match, _ := filepath.Match(m.pattern, file)
  232. return match
  233. }
  234. func (m *moduleSpec) String() string {
  235. // Lock because the type is not atomic. TODO: clean this up.
  236. logging.mu.Lock()
  237. defer logging.mu.Unlock()
  238. var b bytes.Buffer
  239. for i, f := range m.filter {
  240. if i > 0 {
  241. b.WriteRune(',')
  242. }
  243. fmt.Fprintf(&b, "%s=%d", f.pattern, f.level)
  244. }
  245. return b.String()
  246. }
  247. // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
  248. // struct is not exported.
  249. func (m *moduleSpec) Get() interface{} {
  250. return nil
  251. }
  252. var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N")
  253. // Syntax: -vmodule=recordio=2,file=1,gfs*=3
  254. func (m *moduleSpec) Set(value string) error {
  255. var filter []modulePat
  256. for _, pat := range strings.Split(value, ",") {
  257. if len(pat) == 0 {
  258. // Empty strings such as from a trailing comma can be ignored.
  259. continue
  260. }
  261. patLev := strings.Split(pat, "=")
  262. if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {
  263. return errVmoduleSyntax
  264. }
  265. pattern := patLev[0]
  266. v, err := strconv.ParseInt(patLev[1], 10, 32)
  267. if err != nil {
  268. return errors.New("syntax error: expect comma-separated list of filename=N")
  269. }
  270. if v < 0 {
  271. return errors.New("negative value for vmodule level")
  272. }
  273. if v == 0 {
  274. continue // Ignore. It's harmless but no point in paying the overhead.
  275. }
  276. // TODO: check syntax of filter?
  277. filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)})
  278. }
  279. logging.mu.Lock()
  280. defer logging.mu.Unlock()
  281. logging.setVState(logging.verbosity, filter, true)
  282. return nil
  283. }
  284. // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters
  285. // that require filepath.Match to be called to match the pattern.
  286. func isLiteral(pattern string) bool {
  287. return !strings.ContainsAny(pattern, `\*?[]`)
  288. }
  289. // traceLocation represents the setting of the -log_backtrace_at flag.
  290. type traceLocation struct {
  291. file string
  292. line int
  293. }
  294. // isSet reports whether the trace location has been specified.
  295. // logging.mu is held.
  296. func (t *traceLocation) isSet() bool {
  297. return t.line > 0
  298. }
  299. // match reports whether the specified file and line matches the trace location.
  300. // The argument file name is the full path, not the basename specified in the flag.
  301. // logging.mu is held.
  302. func (t *traceLocation) match(file string, line int) bool {
  303. if t.line != line {
  304. return false
  305. }
  306. if i := strings.LastIndex(file, "/"); i >= 0 {
  307. file = file[i+1:]
  308. }
  309. return t.file == file
  310. }
  311. func (t *traceLocation) String() string {
  312. // Lock because the type is not atomic. TODO: clean this up.
  313. logging.mu.Lock()
  314. defer logging.mu.Unlock()
  315. return fmt.Sprintf("%s:%d", t.file, t.line)
  316. }
  317. // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
  318. // struct is not exported
  319. func (t *traceLocation) Get() interface{} {
  320. return nil
  321. }
  322. var errTraceSyntax = errors.New("syntax error: expect file.go:234")
  323. // Syntax: -log_backtrace_at=gopherflakes.go:234
  324. // Note that unlike vmodule the file extension is included here.
  325. func (t *traceLocation) Set(value string) error {
  326. if value == "" {
  327. // Unset.
  328. logging.mu.Lock()
  329. defer logging.mu.Unlock()
  330. t.line = 0
  331. t.file = ""
  332. return nil
  333. }
  334. fields := strings.Split(value, ":")
  335. if len(fields) != 2 {
  336. return errTraceSyntax
  337. }
  338. file, line := fields[0], fields[1]
  339. if !strings.Contains(file, ".") {
  340. return errTraceSyntax
  341. }
  342. v, err := strconv.Atoi(line)
  343. if err != nil {
  344. return errTraceSyntax
  345. }
  346. if v <= 0 {
  347. return errors.New("negative or zero value for level")
  348. }
  349. logging.mu.Lock()
  350. defer logging.mu.Unlock()
  351. t.line = v
  352. t.file = file
  353. return nil
  354. }
  355. // flushSyncWriter is the interface satisfied by logging destinations.
  356. type flushSyncWriter interface {
  357. Flush() error
  358. Sync() error
  359. io.Writer
  360. }
  361. // init sets up the defaults and runs flushDaemon.
  362. func init() {
  363. logging.stderrThreshold = errorLog // Default stderrThreshold is ERROR.
  364. logging.setVState(0, nil, false)
  365. logging.logDir = ""
  366. logging.logFile = ""
  367. logging.logFileMaxSizeMB = 1800
  368. logging.toStderr = true
  369. logging.alsoToStderr = false
  370. logging.skipHeaders = false
  371. logging.addDirHeader = false
  372. logging.skipLogHeaders = false
  373. go logging.flushDaemon()
  374. }
  375. // InitFlags is for explicitly initializing the flags.
  376. func InitFlags(flagset *flag.FlagSet) {
  377. if flagset == nil {
  378. flagset = flag.CommandLine
  379. }
  380. flagset.StringVar(&logging.logDir, "log_dir", logging.logDir, "If non-empty, write log files in this directory")
  381. flagset.StringVar(&logging.logFile, "log_file", logging.logFile, "If non-empty, use this log file")
  382. flagset.Uint64Var(&logging.logFileMaxSizeMB, "log_file_max_size", logging.logFileMaxSizeMB,
  383. "Defines the maximum size a log file can grow to. Unit is megabytes. "+
  384. "If the value is 0, the maximum file size is unlimited.")
  385. flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files")
  386. flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files")
  387. flagset.Var(&logging.verbosity, "v", "number for the log level verbosity")
  388. flagset.BoolVar(&logging.addDirHeader, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header of the log messages")
  389. flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages")
  390. flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files")
  391. flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
  392. flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
  393. flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
  394. }
  395. // Flush flushes all pending log I/O.
  396. func Flush() {
  397. logging.lockAndFlushAll()
  398. }
  399. // loggingT collects all the global state of the logging setup.
  400. type loggingT struct {
  401. // Boolean flags. Not handled atomically because the flag.Value interface
  402. // does not let us avoid the =true, and that shorthand is necessary for
  403. // compatibility. TODO: does this matter enough to fix? Seems unlikely.
  404. toStderr bool // The -logtostderr flag.
  405. alsoToStderr bool // The -alsologtostderr flag.
  406. // Level flag. Handled atomically.
  407. stderrThreshold severity // The -stderrthreshold flag.
  408. // freeList is a list of byte buffers, maintained under freeListMu.
  409. freeList *buffer
  410. // freeListMu maintains the free list. It is separate from the main mutex
  411. // so buffers can be grabbed and printed to without holding the main lock,
  412. // for better parallelization.
  413. freeListMu sync.Mutex
  414. // mu protects the remaining elements of this structure and is
  415. // used to synchronize logging.
  416. mu sync.Mutex
  417. // file holds writer for each of the log types.
  418. file [numSeverity]flushSyncWriter
  419. // pcs is used in V to avoid an allocation when computing the caller's PC.
  420. pcs [1]uintptr
  421. // vmap is a cache of the V Level for each V() call site, identified by PC.
  422. // It is wiped whenever the vmodule flag changes state.
  423. vmap map[uintptr]Level
  424. // filterLength stores the length of the vmodule filter chain. If greater
  425. // than zero, it means vmodule is enabled. It may be read safely
  426. // using sync.LoadInt32, but is only modified under mu.
  427. filterLength int32
  428. // traceLocation is the state of the -log_backtrace_at flag.
  429. traceLocation traceLocation
  430. // These flags are modified only under lock, although verbosity may be fetched
  431. // safely using atomic.LoadInt32.
  432. vmodule moduleSpec // The state of the -vmodule flag.
  433. verbosity Level // V logging level, the value of the -v flag/
  434. // If non-empty, overrides the choice of directory in which to write logs.
  435. // See createLogDirs for the full list of possible destinations.
  436. logDir string
  437. // If non-empty, specifies the path of the file to write logs. mutually exclusive
  438. // with the log_dir option.
  439. logFile string
  440. // When logFile is specified, this limiter makes sure the logFile won't exceeds a certain size. When exceeds, the
  441. // logFile will be cleaned up. If this value is 0, no size limitation will be applied to logFile.
  442. logFileMaxSizeMB uint64
  443. // If true, do not add the prefix headers, useful when used with SetOutput
  444. skipHeaders bool
  445. // If true, do not add the headers to log files
  446. skipLogHeaders bool
  447. // If true, add the file directory to the header
  448. addDirHeader bool
  449. // If set, all output will be redirected unconditionally to the provided logr.Logger
  450. logr logr.Logger
  451. }
  452. // buffer holds a byte Buffer for reuse. The zero value is ready for use.
  453. type buffer struct {
  454. bytes.Buffer
  455. tmp [64]byte // temporary byte array for creating headers.
  456. next *buffer
  457. }
  458. var logging loggingT
  459. // setVState sets a consistent state for V logging.
  460. // l.mu is held.
  461. func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) {
  462. // Turn verbosity off so V will not fire while we are in transition.
  463. l.verbosity.set(0)
  464. // Ditto for filter length.
  465. atomic.StoreInt32(&l.filterLength, 0)
  466. // Set the new filters and wipe the pc->Level map if the filter has changed.
  467. if setFilter {
  468. l.vmodule.filter = filter
  469. l.vmap = make(map[uintptr]Level)
  470. }
  471. // Things are consistent now, so enable filtering and verbosity.
  472. // They are enabled in order opposite to that in V.
  473. atomic.StoreInt32(&l.filterLength, int32(len(filter)))
  474. l.verbosity.set(verbosity)
  475. }
  476. // getBuffer returns a new, ready-to-use buffer.
  477. func (l *loggingT) getBuffer() *buffer {
  478. l.freeListMu.Lock()
  479. b := l.freeList
  480. if b != nil {
  481. l.freeList = b.next
  482. }
  483. l.freeListMu.Unlock()
  484. if b == nil {
  485. b = new(buffer)
  486. } else {
  487. b.next = nil
  488. b.Reset()
  489. }
  490. return b
  491. }
  492. // putBuffer returns a buffer to the free list.
  493. func (l *loggingT) putBuffer(b *buffer) {
  494. if b.Len() >= 256 {
  495. // Let big buffers die a natural death.
  496. return
  497. }
  498. l.freeListMu.Lock()
  499. b.next = l.freeList
  500. l.freeList = b
  501. l.freeListMu.Unlock()
  502. }
  503. var timeNow = time.Now // Stubbed out for testing.
  504. /*
  505. header formats a log header as defined by the C++ implementation.
  506. It returns a buffer containing the formatted header and the user's file and line number.
  507. The depth specifies how many stack frames above lives the source line to be identified in the log message.
  508. Log lines have this form:
  509. Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
  510. where the fields are defined as follows:
  511. L A single character, representing the log level (eg 'I' for INFO)
  512. mm The month (zero padded; ie May is '05')
  513. dd The day (zero padded)
  514. hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
  515. threadid The space-padded thread ID as returned by GetTID()
  516. file The file name
  517. line The line number
  518. msg The user-supplied message
  519. */
  520. func (l *loggingT) header(s severity, depth int) (*buffer, string, int) {
  521. _, file, line, ok := runtime.Caller(3 + depth)
  522. if !ok {
  523. file = "???"
  524. line = 1
  525. } else {
  526. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  527. path := file
  528. file = path[slash+1:]
  529. if l.addDirHeader {
  530. if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 {
  531. file = path[dirsep+1:]
  532. }
  533. }
  534. }
  535. }
  536. return l.formatHeader(s, file, line), file, line
  537. }
  538. // formatHeader formats a log header using the provided file name and line number.
  539. func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
  540. now := timeNow()
  541. if line < 0 {
  542. line = 0 // not a real line number, but acceptable to someDigits
  543. }
  544. if s > fatalLog {
  545. s = infoLog // for safety.
  546. }
  547. buf := l.getBuffer()
  548. if l.skipHeaders {
  549. return buf
  550. }
  551. // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
  552. // It's worth about 3X. Fprintf is hard.
  553. _, month, day := now.Date()
  554. hour, minute, second := now.Clock()
  555. // Lmmdd hh:mm:ss.uuuuuu threadid file:line]
  556. buf.tmp[0] = severityChar[s]
  557. buf.twoDigits(1, int(month))
  558. buf.twoDigits(3, day)
  559. buf.tmp[5] = ' '
  560. buf.twoDigits(6, hour)
  561. buf.tmp[8] = ':'
  562. buf.twoDigits(9, minute)
  563. buf.tmp[11] = ':'
  564. buf.twoDigits(12, second)
  565. buf.tmp[14] = '.'
  566. buf.nDigits(6, 15, now.Nanosecond()/1000, '0')
  567. buf.tmp[21] = ' '
  568. buf.nDigits(7, 22, pid, ' ') // TODO: should be TID
  569. buf.tmp[29] = ' '
  570. buf.Write(buf.tmp[:30])
  571. buf.WriteString(file)
  572. buf.tmp[0] = ':'
  573. n := buf.someDigits(1, line)
  574. buf.tmp[n+1] = ']'
  575. buf.tmp[n+2] = ' '
  576. buf.Write(buf.tmp[:n+3])
  577. return buf
  578. }
  579. // Some custom tiny helper functions to print the log header efficiently.
  580. const digits = "0123456789"
  581. // twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i].
  582. func (buf *buffer) twoDigits(i, d int) {
  583. buf.tmp[i+1] = digits[d%10]
  584. d /= 10
  585. buf.tmp[i] = digits[d%10]
  586. }
  587. // nDigits formats an n-digit integer at buf.tmp[i],
  588. // padding with pad on the left.
  589. // It assumes d >= 0.
  590. func (buf *buffer) nDigits(n, i, d int, pad byte) {
  591. j := n - 1
  592. for ; j >= 0 && d > 0; j-- {
  593. buf.tmp[i+j] = digits[d%10]
  594. d /= 10
  595. }
  596. for ; j >= 0; j-- {
  597. buf.tmp[i+j] = pad
  598. }
  599. }
  600. // someDigits formats a zero-prefixed variable-width integer at buf.tmp[i].
  601. func (buf *buffer) someDigits(i, d int) int {
  602. // Print into the top, then copy down. We know there's space for at least
  603. // a 10-digit number.
  604. j := len(buf.tmp)
  605. for {
  606. j--
  607. buf.tmp[j] = digits[d%10]
  608. d /= 10
  609. if d == 0 {
  610. break
  611. }
  612. }
  613. return copy(buf.tmp[i:], buf.tmp[j:])
  614. }
  615. func (l *loggingT) println(s severity, logr logr.Logger, args ...interface{}) {
  616. buf, file, line := l.header(s, 0)
  617. // if logr is set, we clear the generated header as we rely on the backing
  618. // logr implementation to print headers
  619. if logr != nil {
  620. l.putBuffer(buf)
  621. buf = l.getBuffer()
  622. }
  623. fmt.Fprintln(buf, args...)
  624. l.output(s, logr, buf, file, line, false)
  625. }
  626. func (l *loggingT) print(s severity, logr logr.Logger, args ...interface{}) {
  627. l.printDepth(s, logr, 1, args...)
  628. }
  629. func (l *loggingT) printDepth(s severity, logr logr.Logger, depth int, args ...interface{}) {
  630. buf, file, line := l.header(s, depth)
  631. // if logr is set, we clear the generated header as we rely on the backing
  632. // logr implementation to print headers
  633. if logr != nil {
  634. l.putBuffer(buf)
  635. buf = l.getBuffer()
  636. }
  637. fmt.Fprint(buf, args...)
  638. if buf.Bytes()[buf.Len()-1] != '\n' {
  639. buf.WriteByte('\n')
  640. }
  641. l.output(s, logr, buf, file, line, false)
  642. }
  643. func (l *loggingT) printf(s severity, logr logr.Logger, format string, args ...interface{}) {
  644. buf, file, line := l.header(s, 0)
  645. // if logr is set, we clear the generated header as we rely on the backing
  646. // logr implementation to print headers
  647. if logr != nil {
  648. l.putBuffer(buf)
  649. buf = l.getBuffer()
  650. }
  651. fmt.Fprintf(buf, format, args...)
  652. if buf.Bytes()[buf.Len()-1] != '\n' {
  653. buf.WriteByte('\n')
  654. }
  655. l.output(s, logr, buf, file, line, false)
  656. }
  657. // printWithFileLine behaves like print but uses the provided file and line number. If
  658. // alsoLogToStderr is true, the log message always appears on standard error; it
  659. // will also appear in the log file unless --logtostderr is set.
  660. func (l *loggingT) printWithFileLine(s severity, logr logr.Logger, file string, line int, alsoToStderr bool, args ...interface{}) {
  661. buf := l.formatHeader(s, file, line)
  662. // if logr is set, we clear the generated header as we rely on the backing
  663. // logr implementation to print headers
  664. if logr != nil {
  665. l.putBuffer(buf)
  666. buf = l.getBuffer()
  667. }
  668. fmt.Fprint(buf, args...)
  669. if buf.Bytes()[buf.Len()-1] != '\n' {
  670. buf.WriteByte('\n')
  671. }
  672. l.output(s, logr, buf, file, line, alsoToStderr)
  673. }
  674. // if loggr is specified, will call loggr.Error, otherwise output with logging module.
  675. func (l *loggingT) errorS(err error, loggr logr.Logger, msg string, keysAndValues ...interface{}) {
  676. if loggr != nil {
  677. loggr.Error(err, msg, keysAndValues)
  678. return
  679. }
  680. l.printS(err, msg, keysAndValues...)
  681. }
  682. // if loggr is specified, will call loggr.Info, otherwise output with logging module.
  683. func (l *loggingT) infoS(loggr logr.Logger, msg string, keysAndValues ...interface{}) {
  684. if loggr != nil {
  685. loggr.Info(msg, keysAndValues)
  686. return
  687. }
  688. l.printS(nil, msg, keysAndValues...)
  689. }
  690. // printS is called from infoS and errorS if loggr is not specified.
  691. // if err arguments is specified, will output to errorLog severity
  692. func (l *loggingT) printS(err error, msg string, keysAndValues ...interface{}) {
  693. b := &bytes.Buffer{}
  694. b.WriteString(fmt.Sprintf("%q", msg))
  695. if err != nil {
  696. b.WriteByte(' ')
  697. b.WriteString(fmt.Sprintf("err=%q", err.Error()))
  698. }
  699. kvListFormat(b, keysAndValues...)
  700. var s severity
  701. if err == nil {
  702. s = infoLog
  703. } else {
  704. s = errorLog
  705. }
  706. l.printDepth(s, logging.logr, 2, b)
  707. }
  708. const missingValue = "(MISSING)"
  709. func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
  710. for i := 0; i < len(keysAndValues); i += 2 {
  711. var v interface{}
  712. k := keysAndValues[i]
  713. if i+1 < len(keysAndValues) {
  714. v = keysAndValues[i+1]
  715. } else {
  716. v = missingValue
  717. }
  718. b.WriteByte(' ')
  719. switch v.(type) {
  720. case string, error:
  721. b.WriteString(fmt.Sprintf("%s=%q", k, v))
  722. default:
  723. if _, ok := v.(fmt.Stringer); ok {
  724. b.WriteString(fmt.Sprintf("%s=%q", k, v))
  725. } else {
  726. b.WriteString(fmt.Sprintf("%s=%+v", k, v))
  727. }
  728. }
  729. }
  730. }
  731. // redirectBuffer is used to set an alternate destination for the logs
  732. type redirectBuffer struct {
  733. w io.Writer
  734. }
  735. func (rb *redirectBuffer) Sync() error {
  736. return nil
  737. }
  738. func (rb *redirectBuffer) Flush() error {
  739. return nil
  740. }
  741. func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) {
  742. return rb.w.Write(bytes)
  743. }
  744. // SetLogger will set the backing logr implementation for klog.
  745. // If set, all log lines will be suppressed from the regular Output, and
  746. // redirected to the logr implementation.
  747. // All log lines include the 'severity', 'file' and 'line' values attached as
  748. // structured logging values.
  749. // Use as:
  750. // ...
  751. // klog.SetLogger(zapr.NewLogger(zapLog))
  752. func SetLogger(logr logr.Logger) {
  753. logging.logr = logr
  754. }
  755. // SetOutput sets the output destination for all severities
  756. func SetOutput(w io.Writer) {
  757. logging.mu.Lock()
  758. defer logging.mu.Unlock()
  759. for s := fatalLog; s >= infoLog; s-- {
  760. rb := &redirectBuffer{
  761. w: w,
  762. }
  763. logging.file[s] = rb
  764. }
  765. }
  766. // SetOutputBySeverity sets the output destination for specific severity
  767. func SetOutputBySeverity(name string, w io.Writer) {
  768. logging.mu.Lock()
  769. defer logging.mu.Unlock()
  770. sev, ok := severityByName(name)
  771. if !ok {
  772. panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
  773. }
  774. rb := &redirectBuffer{
  775. w: w,
  776. }
  777. logging.file[sev] = rb
  778. }
  779. // LogToStderr sets whether to log exclusively to stderr, bypassing outputs
  780. func LogToStderr(stderr bool) {
  781. logging.mu.Lock()
  782. defer logging.mu.Unlock()
  783. logging.toStderr = stderr
  784. }
  785. // output writes the data to the log files and releases the buffer.
  786. func (l *loggingT) output(s severity, log logr.Logger, buf *buffer, file string, line int, alsoToStderr bool) {
  787. l.mu.Lock()
  788. if l.traceLocation.isSet() {
  789. if l.traceLocation.match(file, line) {
  790. buf.Write(stacks(false))
  791. }
  792. }
  793. data := buf.Bytes()
  794. if log != nil {
  795. // TODO: set 'severity' and caller information as structured log info
  796. // keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line}
  797. if s == errorLog {
  798. l.logr.Error(nil, string(data))
  799. } else {
  800. log.Info(string(data))
  801. }
  802. } else if l.toStderr {
  803. os.Stderr.Write(data)
  804. } else {
  805. if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
  806. os.Stderr.Write(data)
  807. }
  808. if logging.logFile != "" {
  809. // Since we are using a single log file, all of the items in l.file array
  810. // will point to the same file, so just use one of them to write data.
  811. if l.file[infoLog] == nil {
  812. if err := l.createFiles(infoLog); err != nil {
  813. os.Stderr.Write(data) // Make sure the message appears somewhere.
  814. l.exit(err)
  815. }
  816. }
  817. l.file[infoLog].Write(data)
  818. } else {
  819. if l.file[s] == nil {
  820. if err := l.createFiles(s); err != nil {
  821. os.Stderr.Write(data) // Make sure the message appears somewhere.
  822. l.exit(err)
  823. }
  824. }
  825. switch s {
  826. case fatalLog:
  827. l.file[fatalLog].Write(data)
  828. fallthrough
  829. case errorLog:
  830. l.file[errorLog].Write(data)
  831. fallthrough
  832. case warningLog:
  833. l.file[warningLog].Write(data)
  834. fallthrough
  835. case infoLog:
  836. l.file[infoLog].Write(data)
  837. }
  838. }
  839. }
  840. if s == fatalLog {
  841. // If we got here via Exit rather than Fatal, print no stacks.
  842. if atomic.LoadUint32(&fatalNoStacks) > 0 {
  843. l.mu.Unlock()
  844. timeoutFlush(10 * time.Second)
  845. os.Exit(1)
  846. }
  847. // Dump all goroutine stacks before exiting.
  848. trace := stacks(true)
  849. // Write the stack trace for all goroutines to the stderr.
  850. if l.toStderr || l.alsoToStderr || s >= l.stderrThreshold.get() || alsoToStderr {
  851. os.Stderr.Write(trace)
  852. }
  853. // Write the stack trace for all goroutines to the files.
  854. logExitFunc = func(error) {} // If we get a write error, we'll still exit below.
  855. for log := fatalLog; log >= infoLog; log-- {
  856. if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.
  857. f.Write(trace)
  858. }
  859. }
  860. l.mu.Unlock()
  861. timeoutFlush(10 * time.Second)
  862. os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.
  863. }
  864. l.putBuffer(buf)
  865. l.mu.Unlock()
  866. if stats := severityStats[s]; stats != nil {
  867. atomic.AddInt64(&stats.lines, 1)
  868. atomic.AddInt64(&stats.bytes, int64(len(data)))
  869. }
  870. }
  871. // timeoutFlush calls Flush and returns when it completes or after timeout
  872. // elapses, whichever happens first. This is needed because the hooks invoked
  873. // by Flush may deadlock when klog.Fatal is called from a hook that holds
  874. // a lock.
  875. func timeoutFlush(timeout time.Duration) {
  876. done := make(chan bool, 1)
  877. go func() {
  878. Flush() // calls logging.lockAndFlushAll()
  879. done <- true
  880. }()
  881. select {
  882. case <-done:
  883. case <-time.After(timeout):
  884. fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout)
  885. }
  886. }
  887. // stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines.
  888. func stacks(all bool) []byte {
  889. // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though.
  890. n := 10000
  891. if all {
  892. n = 100000
  893. }
  894. var trace []byte
  895. for i := 0; i < 5; i++ {
  896. trace = make([]byte, n)
  897. nbytes := runtime.Stack(trace, all)
  898. if nbytes < len(trace) {
  899. return trace[:nbytes]
  900. }
  901. n *= 2
  902. }
  903. return trace
  904. }
  905. // logExitFunc provides a simple mechanism to override the default behavior
  906. // of exiting on error. Used in testing and to guarantee we reach a required exit
  907. // for fatal logs. Instead, exit could be a function rather than a method but that
  908. // would make its use clumsier.
  909. var logExitFunc func(error)
  910. // exit is called if there is trouble creating or writing log files.
  911. // It flushes the logs and exits the program; there's no point in hanging around.
  912. // l.mu is held.
  913. func (l *loggingT) exit(err error) {
  914. fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err)
  915. // If logExitFunc is set, we do that instead of exiting.
  916. if logExitFunc != nil {
  917. logExitFunc(err)
  918. return
  919. }
  920. l.flushAll()
  921. os.Exit(2)
  922. }
  923. // syncBuffer joins a bufio.Writer to its underlying file, providing access to the
  924. // file's Sync method and providing a wrapper for the Write method that provides log
  925. // file rotation. There are conflicting methods, so the file cannot be embedded.
  926. // l.mu is held for all its methods.
  927. type syncBuffer struct {
  928. logger *loggingT
  929. *bufio.Writer
  930. file *os.File
  931. sev severity
  932. nbytes uint64 // The number of bytes written to this file
  933. maxbytes uint64 // The max number of bytes this syncBuffer.file can hold before cleaning up.
  934. }
  935. func (sb *syncBuffer) Sync() error {
  936. return sb.file.Sync()
  937. }
  938. // CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options.
  939. func CalculateMaxSize() uint64 {
  940. if logging.logFile != "" {
  941. if logging.logFileMaxSizeMB == 0 {
  942. // If logFileMaxSizeMB is zero, we don't have limitations on the log size.
  943. return math.MaxUint64
  944. }
  945. // Flag logFileMaxSizeMB is in MB for user convenience.
  946. return logging.logFileMaxSizeMB * 1024 * 1024
  947. }
  948. // If "log_file" flag is not specified, the target file (sb.file) will be cleaned up when reaches a fixed size.
  949. return MaxSize
  950. }
  951. func (sb *syncBuffer) Write(p []byte) (n int, err error) {
  952. if sb.nbytes+uint64(len(p)) >= sb.maxbytes {
  953. if err := sb.rotateFile(time.Now(), false); err != nil {
  954. sb.logger.exit(err)
  955. }
  956. }
  957. n, err = sb.Writer.Write(p)
  958. sb.nbytes += uint64(n)
  959. if err != nil {
  960. sb.logger.exit(err)
  961. }
  962. return
  963. }
  964. // rotateFile closes the syncBuffer's file and starts a new one.
  965. // The startup argument indicates whether this is the initial startup of klog.
  966. // If startup is true, existing files are opened for appending instead of truncated.
  967. func (sb *syncBuffer) rotateFile(now time.Time, startup bool) error {
  968. if sb.file != nil {
  969. sb.Flush()
  970. sb.file.Close()
  971. }
  972. var err error
  973. sb.file, _, err = create(severityName[sb.sev], now, startup)
  974. sb.nbytes = 0
  975. if err != nil {
  976. return err
  977. }
  978. sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
  979. if sb.logger.skipLogHeaders {
  980. return nil
  981. }
  982. // Write header.
  983. var buf bytes.Buffer
  984. fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
  985. fmt.Fprintf(&buf, "Running on machine: %s\n", host)
  986. fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
  987. fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n")
  988. n, err := sb.file.Write(buf.Bytes())
  989. sb.nbytes += uint64(n)
  990. return err
  991. }
  992. // bufferSize sizes the buffer associated with each log file. It's large
  993. // so that log records can accumulate without the logging thread blocking
  994. // on disk I/O. The flushDaemon will block instead.
  995. const bufferSize = 256 * 1024
  996. // createFiles creates all the log files for severity from sev down to infoLog.
  997. // l.mu is held.
  998. func (l *loggingT) createFiles(sev severity) error {
  999. now := time.Now()
  1000. // Files are created in decreasing severity order, so as soon as we find one
  1001. // has already been created, we can stop.
  1002. for s := sev; s >= infoLog && l.file[s] == nil; s-- {
  1003. sb := &syncBuffer{
  1004. logger: l,
  1005. sev: s,
  1006. maxbytes: CalculateMaxSize(),
  1007. }
  1008. if err := sb.rotateFile(now, true); err != nil {
  1009. return err
  1010. }
  1011. l.file[s] = sb
  1012. }
  1013. return nil
  1014. }
  1015. const flushInterval = 5 * time.Second
  1016. // flushDaemon periodically flushes the log file buffers.
  1017. func (l *loggingT) flushDaemon() {
  1018. for range time.NewTicker(flushInterval).C {
  1019. l.lockAndFlushAll()
  1020. }
  1021. }
  1022. // lockAndFlushAll is like flushAll but locks l.mu first.
  1023. func (l *loggingT) lockAndFlushAll() {
  1024. l.mu.Lock()
  1025. l.flushAll()
  1026. l.mu.Unlock()
  1027. }
  1028. // flushAll flushes all the logs and attempts to "sync" their data to disk.
  1029. // l.mu is held.
  1030. func (l *loggingT) flushAll() {
  1031. // Flush from fatal down, in case there's trouble flushing.
  1032. for s := fatalLog; s >= infoLog; s-- {
  1033. file := l.file[s]
  1034. if file != nil {
  1035. file.Flush() // ignore error
  1036. file.Sync() // ignore error
  1037. }
  1038. }
  1039. }
  1040. // CopyStandardLogTo arranges for messages written to the Go "log" package's
  1041. // default logs to also appear in the Google logs for the named and lower
  1042. // severities. Subsequent changes to the standard log's default output location
  1043. // or format may break this behavior.
  1044. //
  1045. // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
  1046. // recognized, CopyStandardLogTo panics.
  1047. func CopyStandardLogTo(name string) {
  1048. sev, ok := severityByName(name)
  1049. if !ok {
  1050. panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
  1051. }
  1052. // Set a log format that captures the user's file and line:
  1053. // d.go:23: message
  1054. stdLog.SetFlags(stdLog.Lshortfile)
  1055. stdLog.SetOutput(logBridge(sev))
  1056. }
  1057. // logBridge provides the Write method that enables CopyStandardLogTo to connect
  1058. // Go's standard logs to the logs provided by this package.
  1059. type logBridge severity
  1060. // Write parses the standard logging line and passes its components to the
  1061. // logger for severity(lb).
  1062. func (lb logBridge) Write(b []byte) (n int, err error) {
  1063. var (
  1064. file = "???"
  1065. line = 1
  1066. text string
  1067. )
  1068. // Split "d.go:23: message" into "d.go", "23", and "message".
  1069. if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
  1070. text = fmt.Sprintf("bad log format: %s", b)
  1071. } else {
  1072. file = string(parts[0])
  1073. text = string(parts[2][1:]) // skip leading space
  1074. line, err = strconv.Atoi(string(parts[1]))
  1075. if err != nil {
  1076. text = fmt.Sprintf("bad line number: %s", b)
  1077. line = 1
  1078. }
  1079. }
  1080. // printWithFileLine with alsoToStderr=true, so standard log messages
  1081. // always appear on standard error.
  1082. logging.printWithFileLine(severity(lb), logging.logr, file, line, true, text)
  1083. return len(b), nil
  1084. }
  1085. // setV computes and remembers the V level for a given PC
  1086. // when vmodule is enabled.
  1087. // File pattern matching takes the basename of the file, stripped
  1088. // of its .go suffix, and uses filepath.Match, which is a little more
  1089. // general than the *? matching used in C++.
  1090. // l.mu is held.
  1091. func (l *loggingT) setV(pc uintptr) Level {
  1092. fn := runtime.FuncForPC(pc)
  1093. file, _ := fn.FileLine(pc)
  1094. // The file is something like /a/b/c/d.go. We want just the d.
  1095. if strings.HasSuffix(file, ".go") {
  1096. file = file[:len(file)-3]
  1097. }
  1098. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  1099. file = file[slash+1:]
  1100. }
  1101. for _, filter := range l.vmodule.filter {
  1102. if filter.match(file) {
  1103. l.vmap[pc] = filter.level
  1104. return filter.level
  1105. }
  1106. }
  1107. l.vmap[pc] = 0
  1108. return 0
  1109. }
  1110. // Verbose is a boolean type that implements Infof (like Printf) etc.
  1111. // See the documentation of V for more information.
  1112. type Verbose struct {
  1113. enabled bool
  1114. logr logr.Logger
  1115. }
  1116. func newVerbose(level Level, b bool) Verbose {
  1117. if logging.logr == nil {
  1118. return Verbose{b, nil}
  1119. }
  1120. return Verbose{b, logging.logr.V(int(level))}
  1121. }
  1122. // V reports whether verbosity at the call site is at least the requested level.
  1123. // The returned value is a struct of type Verbose, which implements Info, Infoln
  1124. // and Infof. These methods will write to the Info log if called.
  1125. // Thus, one may write either
  1126. // if glog.V(2).Enabled() { klog.Info("log this") }
  1127. // or
  1128. // klog.V(2).Info("log this")
  1129. // The second form is shorter but the first is cheaper if logging is off because it does
  1130. // not evaluate its arguments.
  1131. //
  1132. // Whether an individual call to V generates a log record depends on the setting of
  1133. // the -v and -vmodule flags; both are off by default. The V call will log if its level
  1134. // is less than or equal to the value of the -v flag, or alternatively if its level is
  1135. // less than or equal to the value of the -vmodule pattern matching the source file
  1136. // containing the call.
  1137. func V(level Level) Verbose {
  1138. // This function tries hard to be cheap unless there's work to do.
  1139. // The fast path is two atomic loads and compares.
  1140. // Here is a cheap but safe test to see if V logging is enabled globally.
  1141. if logging.verbosity.get() >= level {
  1142. return newVerbose(level, true)
  1143. }
  1144. // It's off globally but it vmodule may still be set.
  1145. // Here is another cheap but safe test to see if vmodule is enabled.
  1146. if atomic.LoadInt32(&logging.filterLength) > 0 {
  1147. // Now we need a proper lock to use the logging structure. The pcs field
  1148. // is shared so we must lock before accessing it. This is fairly expensive,
  1149. // but if V logging is enabled we're slow anyway.
  1150. logging.mu.Lock()
  1151. defer logging.mu.Unlock()
  1152. if runtime.Callers(2, logging.pcs[:]) == 0 {
  1153. return newVerbose(level, false)
  1154. }
  1155. v, ok := logging.vmap[logging.pcs[0]]
  1156. if !ok {
  1157. v = logging.setV(logging.pcs[0])
  1158. }
  1159. return newVerbose(level, v >= level)
  1160. }
  1161. return newVerbose(level, false)
  1162. }
  1163. // Enabled will return true if this log level is enabled, guarded by the value
  1164. // of v.
  1165. // See the documentation of V for usage.
  1166. func (v Verbose) Enabled() bool {
  1167. return v.enabled
  1168. }
  1169. // Info is equivalent to the global Info function, guarded by the value of v.
  1170. // See the documentation of V for usage.
  1171. func (v Verbose) Info(args ...interface{}) {
  1172. if v.enabled {
  1173. logging.print(infoLog, v.logr, args...)
  1174. }
  1175. }
  1176. // Infoln is equivalent to the global Infoln function, guarded by the value of v.
  1177. // See the documentation of V for usage.
  1178. func (v Verbose) Infoln(args ...interface{}) {
  1179. if v.enabled {
  1180. logging.println(infoLog, v.logr, args...)
  1181. }
  1182. }
  1183. // Infof is equivalent to the global Infof function, guarded by the value of v.
  1184. // See the documentation of V for usage.
  1185. func (v Verbose) Infof(format string, args ...interface{}) {
  1186. if v.enabled {
  1187. logging.printf(infoLog, v.logr, format, args...)
  1188. }
  1189. }
  1190. // InfoS is equivalent to the global InfoS function, guarded by the value of v.
  1191. // See the documentation of V for usage.
  1192. func (v Verbose) InfoS(msg string, keysAndValues ...interface{}) {
  1193. if v.enabled {
  1194. logging.infoS(v.logr, msg, keysAndValues...)
  1195. }
  1196. }
  1197. // Error is equivalent to the global Error function, guarded by the value of v.
  1198. // See the documentation of V for usage.
  1199. func (v Verbose) Error(err error, msg string, args ...interface{}) {
  1200. if v.enabled {
  1201. logging.errorS(err, v.logr, msg, args...)
  1202. }
  1203. }
  1204. // Info logs to the INFO log.
  1205. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1206. func Info(args ...interface{}) {
  1207. logging.print(infoLog, logging.logr, args...)
  1208. }
  1209. // InfoDepth acts as Info but uses depth to determine which call frame to log.
  1210. // InfoDepth(0, "msg") is the same as Info("msg").
  1211. func InfoDepth(depth int, args ...interface{}) {
  1212. logging.printDepth(infoLog, logging.logr, depth, args...)
  1213. }
  1214. // Infoln logs to the INFO log.
  1215. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1216. func Infoln(args ...interface{}) {
  1217. logging.println(infoLog, logging.logr, args...)
  1218. }
  1219. // Infof logs to the INFO log.
  1220. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1221. func Infof(format string, args ...interface{}) {
  1222. logging.printf(infoLog, logging.logr, format, args...)
  1223. }
  1224. // InfoS structured logs to the INFO log.
  1225. // The msg argument used to add constant description to the log line.
  1226. // The key/value pairs would be join by "=" ; a newline is always appended.
  1227. //
  1228. // Basic examples:
  1229. // >> klog.InfoS("Pod status updated", "pod", "kubedns", "status", "ready")
  1230. // output:
  1231. // >> I1025 00:15:15.525108 1 controller_utils.go:116] "Pod status updated" pod="kubedns" status="ready"
  1232. func InfoS(msg string, keysAndValues ...interface{}) {
  1233. logging.infoS(logging.logr, msg, keysAndValues...)
  1234. }
  1235. // Warning logs to the WARNING and INFO logs.
  1236. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1237. func Warning(args ...interface{}) {
  1238. logging.print(warningLog, logging.logr, args...)
  1239. }
  1240. // WarningDepth acts as Warning but uses depth to determine which call frame to log.
  1241. // WarningDepth(0, "msg") is the same as Warning("msg").
  1242. func WarningDepth(depth int, args ...interface{}) {
  1243. logging.printDepth(warningLog, logging.logr, depth, args...)
  1244. }
  1245. // Warningln logs to the WARNING and INFO logs.
  1246. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1247. func Warningln(args ...interface{}) {
  1248. logging.println(warningLog, logging.logr, args...)
  1249. }
  1250. // Warningf logs to the WARNING and INFO logs.
  1251. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1252. func Warningf(format string, args ...interface{}) {
  1253. logging.printf(warningLog, logging.logr, format, args...)
  1254. }
  1255. // Error logs to the ERROR, WARNING, and INFO logs.
  1256. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1257. func Error(args ...interface{}) {
  1258. logging.print(errorLog, logging.logr, args...)
  1259. }
  1260. // ErrorDepth acts as Error but uses depth to determine which call frame to log.
  1261. // ErrorDepth(0, "msg") is the same as Error("msg").
  1262. func ErrorDepth(depth int, args ...interface{}) {
  1263. logging.printDepth(errorLog, logging.logr, depth, args...)
  1264. }
  1265. // Errorln logs to the ERROR, WARNING, and INFO logs.
  1266. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1267. func Errorln(args ...interface{}) {
  1268. logging.println(errorLog, logging.logr, args...)
  1269. }
  1270. // Errorf logs to the ERROR, WARNING, and INFO logs.
  1271. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1272. func Errorf(format string, args ...interface{}) {
  1273. logging.printf(errorLog, logging.logr, format, args...)
  1274. }
  1275. // ErrorS structured logs to the ERROR, WARNING, and INFO logs.
  1276. // the err argument used as "err" field of log line.
  1277. // The msg argument used to add constant description to the log line.
  1278. // The key/value pairs would be join by "=" ; a newline is always appended.
  1279. //
  1280. // Basic examples:
  1281. // >> klog.ErrorS(err, "Failed to update pod status")
  1282. // output:
  1283. // >> E1025 00:15:15.525108 1 controller_utils.go:114] "Failed to update pod status" err="timeout"
  1284. func ErrorS(err error, msg string, keysAndValues ...interface{}) {
  1285. logging.errorS(err, logging.logr, msg, keysAndValues...)
  1286. }
  1287. // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
  1288. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1289. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1290. func Fatal(args ...interface{}) {
  1291. logging.print(fatalLog, logging.logr, args...)
  1292. }
  1293. // FatalDepth acts as Fatal but uses depth to determine which call frame to log.
  1294. // FatalDepth(0, "msg") is the same as Fatal("msg").
  1295. func FatalDepth(depth int, args ...interface{}) {
  1296. logging.printDepth(fatalLog, logging.logr, depth, args...)
  1297. }
  1298. // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
  1299. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1300. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1301. func Fatalln(args ...interface{}) {
  1302. logging.println(fatalLog, logging.logr, args...)
  1303. }
  1304. // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs,
  1305. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1306. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1307. func Fatalf(format string, args ...interface{}) {
  1308. logging.printf(fatalLog, logging.logr, format, args...)
  1309. }
  1310. // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks.
  1311. // It allows Exit and relatives to use the Fatal logs.
  1312. var fatalNoStacks uint32
  1313. // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1314. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1315. func Exit(args ...interface{}) {
  1316. atomic.StoreUint32(&fatalNoStacks, 1)
  1317. logging.print(fatalLog, logging.logr, args...)
  1318. }
  1319. // ExitDepth acts as Exit but uses depth to determine which call frame to log.
  1320. // ExitDepth(0, "msg") is the same as Exit("msg").
  1321. func ExitDepth(depth int, args ...interface{}) {
  1322. atomic.StoreUint32(&fatalNoStacks, 1)
  1323. logging.printDepth(fatalLog, logging.logr, depth, args...)
  1324. }
  1325. // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1326. func Exitln(args ...interface{}) {
  1327. atomic.StoreUint32(&fatalNoStacks, 1)
  1328. logging.println(fatalLog, logging.logr, args...)
  1329. }
  1330. // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1331. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1332. func Exitf(format string, args ...interface{}) {
  1333. atomic.StoreUint32(&fatalNoStacks, 1)
  1334. logging.printf(fatalLog, logging.logr, format, args...)
  1335. }
  1336. // ObjectRef references a kubernetes object
  1337. type ObjectRef struct {
  1338. Name string `json:"name"`
  1339. Namespace string `json:"namespace,omitempty"`
  1340. }
  1341. func (ref ObjectRef) String() string {
  1342. if ref.Namespace != "" {
  1343. return fmt.Sprintf("%s/%s", ref.Namespace, ref.Name)
  1344. }
  1345. return ref.Name
  1346. }
  1347. // KMetadata is a subset of the kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface
  1348. // this interface may expand in the future, but will always be a subset of the
  1349. // kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface
  1350. type KMetadata interface {
  1351. GetName() string
  1352. GetNamespace() string
  1353. }
  1354. // KObj returns ObjectRef from ObjectMeta
  1355. func KObj(obj KMetadata) ObjectRef {
  1356. return ObjectRef{
  1357. Name: obj.GetName(),
  1358. Namespace: obj.GetNamespace(),
  1359. }
  1360. }
  1361. // KRef returns ObjectRef from name and namespace
  1362. func KRef(namespace, name string) ObjectRef {
  1363. return ObjectRef{
  1364. Name: name,
  1365. Namespace: namespace,
  1366. }
  1367. }