klog.go 51 KB

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