klog.go 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  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 contains the following functionality:
  17. //
  18. // - output routing as defined via command line flags ([InitFlags])
  19. // - log formatting as text, either with a single, unstructured string ([Info], [Infof], etc.)
  20. // or as a structured log entry with message and key/value pairs ([InfoS], etc.)
  21. // - management of a go-logr [Logger] ([SetLogger], [Background], [TODO])
  22. // - helper functions for logging values ([Format]) and managing the state of klog ([CaptureState], [State.Restore])
  23. // - wrappers for [logr] APIs for contextual logging where the wrappers can
  24. // be turned into no-ops ([EnableContextualLogging], [NewContext], [FromContext],
  25. // [LoggerWithValues], [LoggerWithName]); if the ability to turn off
  26. // contextual logging is not needed, then go-logr can also be used directly
  27. // - type aliases for go-logr types to simplify imports in code which uses both (e.g. [Logger])
  28. // - [k8s.io/klog/v2/textlogger]: a logger which uses the same formatting as klog log with
  29. // simpler output routing; beware that it comes with its own command line flags
  30. // and does not use the ones from klog
  31. // - [k8s.io/klog/v2/ktesting]: per-test output in Go unit tests
  32. // - [k8s.io/klog/v2/klogr]: a deprecated, standalone [logr.Logger] on top of the main klog package;
  33. // use [Background] instead if klog output routing is needed, [k8s.io/klog/v2/textlogger] if not
  34. // - [k8s.io/klog/v2/examples]: demos of this functionality
  35. // - [k8s.io/klog/v2/test]: reusable tests for [logr.Logger] implementations
  36. //
  37. // Basic examples:
  38. //
  39. // klog.Info("Prepare to repel boarders")
  40. //
  41. // klog.Fatalf("Initialization failed: %s", err)
  42. //
  43. // See the documentation for the V function for an explanation of these examples:
  44. //
  45. // if klog.V(2) {
  46. // klog.Info("Starting transaction...")
  47. // }
  48. //
  49. // klog.V(2).Infoln("Processed", nItems, "elements")
  50. //
  51. // Log output is buffered and written periodically using Flush. Programs
  52. // should call Flush before exiting to guarantee all log output is written.
  53. //
  54. // By default, all log statements write to standard error.
  55. // This package provides several flags that modify this behavior.
  56. // As a result, flag.Parse must be called before any logging is done.
  57. //
  58. // -logtostderr=true
  59. // Logs are written to standard error instead of to files.
  60. // This shortcuts most of the usual output routing:
  61. // -alsologtostderr, -stderrthreshold and -log_dir have no
  62. // effect and output redirection at runtime with SetOutput is
  63. // ignored.
  64. // -alsologtostderr=false
  65. // Logs are written to standard error as well as to files.
  66. // -stderrthreshold=ERROR
  67. // Log events at or above this severity are logged to standard
  68. // error as well as to files.
  69. // -log_dir=""
  70. // Log files will be written to this directory instead of the
  71. // default temporary directory.
  72. //
  73. // Other flags provide aids to debugging.
  74. //
  75. // -log_backtrace_at=""
  76. // When set to a file and line number holding a logging statement,
  77. // such as
  78. // -log_backtrace_at=gopherflakes.go:234
  79. // a stack trace will be written to the Info log whenever execution
  80. // hits that statement. (Unlike with -vmodule, the ".go" must be
  81. // present.)
  82. // -v=0
  83. // Enable V-leveled logging at the specified level.
  84. // -vmodule=""
  85. // The syntax of the argument is a comma-separated list of pattern=N,
  86. // where pattern is a literal file name (minus the ".go" suffix) or
  87. // "glob" pattern and N is a V level. For instance,
  88. // -vmodule=gopher*=3
  89. // sets the V level to 3 in all Go files whose names begin "gopher".
  90. package klog
  91. import (
  92. "bufio"
  93. "bytes"
  94. "errors"
  95. "flag"
  96. "fmt"
  97. "io"
  98. stdLog "log"
  99. "math"
  100. "os"
  101. "path/filepath"
  102. "runtime"
  103. "strconv"
  104. "strings"
  105. "sync"
  106. "sync/atomic"
  107. "time"
  108. "k8s.io/klog/v2/internal/buffer"
  109. "k8s.io/klog/v2/internal/clock"
  110. "k8s.io/klog/v2/internal/dbg"
  111. "k8s.io/klog/v2/internal/serialize"
  112. "k8s.io/klog/v2/internal/severity"
  113. )
  114. // severityValue identifies the sort of log: info, warning etc. It also implements
  115. // the flag.Value interface. The -stderrthreshold flag is of type severity and
  116. // should be modified only through the flag.Value interface. The values match
  117. // the corresponding constants in C++.
  118. type severityValue struct {
  119. severity.Severity
  120. }
  121. // get returns the value of the severity.
  122. func (s *severityValue) get() severity.Severity {
  123. return severity.Severity(atomic.LoadInt32((*int32)(&s.Severity)))
  124. }
  125. // set sets the value of the severity.
  126. func (s *severityValue) set(val severity.Severity) {
  127. atomic.StoreInt32((*int32)(&s.Severity), int32(val))
  128. }
  129. // String is part of the flag.Value interface.
  130. func (s *severityValue) String() string {
  131. return strconv.FormatInt(int64(s.Severity), 10)
  132. }
  133. // Get is part of the flag.Getter interface.
  134. func (s *severityValue) Get() interface{} {
  135. return s.Severity
  136. }
  137. // Set is part of the flag.Value interface.
  138. func (s *severityValue) Set(value string) error {
  139. var threshold severity.Severity
  140. // Is it a known name?
  141. if v, ok := severity.ByName(value); ok {
  142. threshold = v
  143. } else {
  144. v, err := strconv.ParseInt(value, 10, 32)
  145. if err != nil {
  146. return err
  147. }
  148. threshold = severity.Severity(v)
  149. }
  150. logging.stderrThreshold.set(threshold)
  151. return nil
  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 = [severity.NumSeverity]*OutputStats{
  172. severity.InfoLog: &Stats.Info,
  173. severity.WarningLog: &Stats.Warning,
  174. severity.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. return m.serialize()
  239. }
  240. func (m *moduleSpec) serialize() string {
  241. var b bytes.Buffer
  242. for i, f := range m.filter {
  243. if i > 0 {
  244. b.WriteRune(',')
  245. }
  246. fmt.Fprintf(&b, "%s=%d", f.pattern, f.level)
  247. }
  248. return b.String()
  249. }
  250. // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
  251. // struct is not exported.
  252. func (m *moduleSpec) Get() interface{} {
  253. return nil
  254. }
  255. var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N")
  256. // Set will sets module value
  257. // Syntax: -vmodule=recordio=2,file=1,gfs*=3
  258. func (m *moduleSpec) Set(value string) error {
  259. filter, err := parseModuleSpec(value)
  260. if err != nil {
  261. return err
  262. }
  263. logging.mu.Lock()
  264. defer logging.mu.Unlock()
  265. logging.setVState(logging.verbosity, filter, true)
  266. return nil
  267. }
  268. func parseModuleSpec(value string) ([]modulePat, error) {
  269. var filter []modulePat
  270. for _, pat := range strings.Split(value, ",") {
  271. if len(pat) == 0 {
  272. // Empty strings such as from a trailing comma can be ignored.
  273. continue
  274. }
  275. patLev := strings.Split(pat, "=")
  276. if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {
  277. return nil, errVmoduleSyntax
  278. }
  279. pattern := patLev[0]
  280. v, err := strconv.ParseInt(patLev[1], 10, 32)
  281. if err != nil {
  282. return nil, errors.New("syntax error: expect comma-separated list of filename=N")
  283. }
  284. if v < 0 {
  285. return nil, errors.New("negative value for vmodule level")
  286. }
  287. if v == 0 {
  288. continue // Ignore. It's harmless but no point in paying the overhead.
  289. }
  290. // TODO: check syntax of filter?
  291. filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)})
  292. }
  293. return filter, nil
  294. }
  295. // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters
  296. // that require filepath.Match to be called to match the pattern.
  297. func isLiteral(pattern string) bool {
  298. return !strings.ContainsAny(pattern, `\*?[]`)
  299. }
  300. // traceLocation represents the setting of the -log_backtrace_at flag.
  301. type traceLocation struct {
  302. file string
  303. line int
  304. }
  305. // isSet reports whether the trace location has been specified.
  306. // logging.mu is held.
  307. func (t *traceLocation) isSet() bool {
  308. return t.line > 0
  309. }
  310. // match reports whether the specified file and line matches the trace location.
  311. // The argument file name is the full path, not the basename specified in the flag.
  312. // logging.mu is held.
  313. func (t *traceLocation) match(file string, line int) bool {
  314. if t.line != line {
  315. return false
  316. }
  317. if i := strings.LastIndex(file, "/"); i >= 0 {
  318. file = file[i+1:]
  319. }
  320. return t.file == file
  321. }
  322. func (t *traceLocation) String() string {
  323. // Lock because the type is not atomic. TODO: clean this up.
  324. logging.mu.Lock()
  325. defer logging.mu.Unlock()
  326. return fmt.Sprintf("%s:%d", t.file, t.line)
  327. }
  328. // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
  329. // struct is not exported
  330. func (t *traceLocation) Get() interface{} {
  331. return nil
  332. }
  333. var errTraceSyntax = errors.New("syntax error: expect file.go:234")
  334. // Set will sets backtrace value
  335. // Syntax: -log_backtrace_at=gopherflakes.go:234
  336. // Note that unlike vmodule the file extension is included here.
  337. func (t *traceLocation) Set(value string) error {
  338. if value == "" {
  339. // Unset.
  340. logging.mu.Lock()
  341. defer logging.mu.Unlock()
  342. t.line = 0
  343. t.file = ""
  344. return nil
  345. }
  346. fields := strings.Split(value, ":")
  347. if len(fields) != 2 {
  348. return errTraceSyntax
  349. }
  350. file, line := fields[0], fields[1]
  351. if !strings.Contains(file, ".") {
  352. return errTraceSyntax
  353. }
  354. v, err := strconv.Atoi(line)
  355. if err != nil {
  356. return errTraceSyntax
  357. }
  358. if v <= 0 {
  359. return errors.New("negative or zero value for level")
  360. }
  361. logging.mu.Lock()
  362. defer logging.mu.Unlock()
  363. t.line = v
  364. t.file = file
  365. return nil
  366. }
  367. var logging loggingT
  368. var commandLine flag.FlagSet
  369. // init sets up the defaults and creates command line flags.
  370. func init() {
  371. commandLine.StringVar(&logging.logDir, "log_dir", "", "If non-empty, write log files in this directory (no effect when -logtostderr=true)")
  372. commandLine.StringVar(&logging.logFile, "log_file", "", "If non-empty, use this log file (no effect when -logtostderr=true)")
  373. commandLine.Uint64Var(&logging.logFileMaxSizeMB, "log_file_max_size", 1800,
  374. "Defines the maximum size a log file can grow to (no effect when -logtostderr=true). Unit is megabytes. "+
  375. "If the value is 0, the maximum file size is unlimited.")
  376. commandLine.BoolVar(&logging.toStderr, "logtostderr", true, "log to standard error instead of files")
  377. commandLine.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files (no effect when -logtostderr=true)")
  378. logging.setVState(0, nil, false)
  379. commandLine.Var(&logging.verbosity, "v", "number for the log level verbosity")
  380. commandLine.BoolVar(&logging.addDirHeader, "add_dir_header", false, "If true, adds the file directory to the header of the log messages")
  381. commandLine.BoolVar(&logging.skipHeaders, "skip_headers", false, "If true, avoid header prefixes in the log messages")
  382. commandLine.BoolVar(&logging.oneOutput, "one_output", false, "If true, only write logs to their native severity level (vs also writing to each lower severity level; no effect when -logtostderr=true)")
  383. commandLine.BoolVar(&logging.skipLogHeaders, "skip_log_headers", false, "If true, avoid headers when opening log files (no effect when -logtostderr=true)")
  384. logging.stderrThreshold = severityValue{
  385. Severity: severity.ErrorLog, // Default stderrThreshold is ERROR.
  386. }
  387. commandLine.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr when writing to files and stderr (no effect when -logtostderr=true or -alsologtostderr=true)")
  388. commandLine.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
  389. commandLine.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
  390. logging.settings.contextualLoggingEnabled = true
  391. logging.flushD = newFlushDaemon(logging.lockAndFlushAll, nil)
  392. }
  393. // InitFlags is for explicitly initializing the flags.
  394. // It may get called repeatedly for different flagsets, but not
  395. // twice for the same one. May get called concurrently
  396. // to other goroutines using klog. However, only some flags
  397. // may get set concurrently (see implementation).
  398. func InitFlags(flagset *flag.FlagSet) {
  399. if flagset == nil {
  400. flagset = flag.CommandLine
  401. }
  402. commandLine.VisitAll(func(f *flag.Flag) {
  403. flagset.Var(f.Value, f.Name, f.Usage)
  404. })
  405. }
  406. // Flush flushes all pending log I/O.
  407. func Flush() {
  408. logging.lockAndFlushAll()
  409. }
  410. // settings collects global settings.
  411. type settings struct {
  412. // contextualLoggingEnabled controls whether contextual logging is
  413. // active. Disabling it may have some small performance benefit.
  414. contextualLoggingEnabled bool
  415. // logger is the global Logger chosen by users of klog, nil if
  416. // none is available.
  417. logger *logWriter
  418. // loggerOptions contains the options that were supplied for
  419. // globalLogger.
  420. loggerOptions loggerOptions
  421. // Boolean flags. Not handled atomically because the flag.Value interface
  422. // does not let us avoid the =true, and that shorthand is necessary for
  423. // compatibility. TODO: does this matter enough to fix? Seems unlikely.
  424. toStderr bool // The -logtostderr flag.
  425. alsoToStderr bool // The -alsologtostderr flag.
  426. // Level flag. Handled atomically.
  427. stderrThreshold severityValue // The -stderrthreshold flag.
  428. // Access to all of the following fields must be protected via a mutex.
  429. // file holds writer for each of the log types.
  430. file [severity.NumSeverity]io.Writer
  431. // flushInterval is the interval for periodic flushing. If zero,
  432. // the global default will be used.
  433. flushInterval time.Duration
  434. // filterLength stores the length of the vmodule filter chain. If greater
  435. // than zero, it means vmodule is enabled. It may be read safely
  436. // using sync.LoadInt32, but is only modified under mu.
  437. filterLength int32
  438. // traceLocation is the state of the -log_backtrace_at flag.
  439. traceLocation traceLocation
  440. // These flags are modified only under lock, although verbosity may be fetched
  441. // safely using atomic.LoadInt32.
  442. vmodule moduleSpec // The state of the -vmodule flag.
  443. verbosity Level // V logging level, the value of the -v flag/
  444. // If non-empty, overrides the choice of directory in which to write logs.
  445. // See createLogDirs for the full list of possible destinations.
  446. logDir string
  447. // If non-empty, specifies the path of the file to write logs. mutually exclusive
  448. // with the log_dir option.
  449. logFile string
  450. // When logFile is specified, this limiter makes sure the logFile won't exceeds a certain size. When exceeds, the
  451. // logFile will be cleaned up. If this value is 0, no size limitation will be applied to logFile.
  452. logFileMaxSizeMB uint64
  453. // If true, do not add the prefix headers, useful when used with SetOutput
  454. skipHeaders bool
  455. // If true, do not add the headers to log files
  456. skipLogHeaders bool
  457. // If true, add the file directory to the header
  458. addDirHeader bool
  459. // If true, messages will not be propagated to lower severity log levels
  460. oneOutput bool
  461. // If set, all output will be filtered through the filter.
  462. filter LogFilter
  463. }
  464. // deepCopy creates a copy that doesn't share anything with the original
  465. // instance.
  466. func (s settings) deepCopy() settings {
  467. // vmodule is a slice and would be shared, so we have copy it.
  468. filter := make([]modulePat, len(s.vmodule.filter))
  469. copy(filter, s.vmodule.filter)
  470. s.vmodule.filter = filter
  471. if s.logger != nil {
  472. logger := *s.logger
  473. s.logger = &logger
  474. }
  475. return s
  476. }
  477. // loggingT collects all the global state of the logging setup.
  478. type loggingT struct {
  479. settings
  480. // flushD holds a flushDaemon that frequently flushes log file buffers.
  481. // Uses its own mutex.
  482. flushD *flushDaemon
  483. // mu protects the remaining elements of this structure and the fields
  484. // in settingsT which need a mutex lock.
  485. mu sync.Mutex
  486. // pcs is used in V to avoid an allocation when computing the caller's PC.
  487. pcs [1]uintptr
  488. // vmap is a cache of the V Level for each V() call site, identified by PC.
  489. // It is wiped whenever the vmodule flag changes state.
  490. vmap map[uintptr]Level
  491. }
  492. // setVState sets a consistent state for V logging.
  493. // l.mu is held.
  494. func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) {
  495. // Turn verbosity off so V will not fire while we are in transition.
  496. l.verbosity.set(0)
  497. // Ditto for filter length.
  498. atomic.StoreInt32(&l.filterLength, 0)
  499. // Set the new filters and wipe the pc->Level map if the filter has changed.
  500. if setFilter {
  501. l.vmodule.filter = filter
  502. l.vmap = make(map[uintptr]Level)
  503. }
  504. // Things are consistent now, so enable filtering and verbosity.
  505. // They are enabled in order opposite to that in V.
  506. atomic.StoreInt32(&l.filterLength, int32(len(filter)))
  507. l.verbosity.set(verbosity)
  508. }
  509. var timeNow = time.Now // Stubbed out for testing.
  510. // CaptureState gathers information about all current klog settings.
  511. // The result can be used to restore those settings.
  512. func CaptureState() State {
  513. logging.mu.Lock()
  514. defer logging.mu.Unlock()
  515. return &state{
  516. settings: logging.settings.deepCopy(),
  517. flushDRunning: logging.flushD.isRunning(),
  518. maxSize: MaxSize,
  519. }
  520. }
  521. // State stores a snapshot of klog settings. It gets created with CaptureState
  522. // and can be used to restore the entire state. Modifying individual settings
  523. // is supported via the command line flags.
  524. type State interface {
  525. // Restore restore the entire state. It may get called more than once.
  526. Restore()
  527. }
  528. type state struct {
  529. settings
  530. flushDRunning bool
  531. maxSize uint64
  532. }
  533. func (s *state) Restore() {
  534. // This needs to be done before mutex locking.
  535. if s.flushDRunning && !logging.flushD.isRunning() {
  536. // This is not quite accurate: StartFlushDaemon might
  537. // have been called with some different interval.
  538. interval := s.flushInterval
  539. if interval == 0 {
  540. interval = flushInterval
  541. }
  542. logging.flushD.run(interval)
  543. } else if !s.flushDRunning && logging.flushD.isRunning() {
  544. logging.flushD.stop()
  545. }
  546. logging.mu.Lock()
  547. defer logging.mu.Unlock()
  548. logging.settings = s.settings
  549. logging.setVState(s.verbosity, s.vmodule.filter, true)
  550. MaxSize = s.maxSize
  551. }
  552. /*
  553. header formats a log header as defined by the C++ implementation.
  554. It returns a buffer containing the formatted header and the user's file and line number.
  555. The depth specifies how many stack frames above lives the source line to be identified in the log message.
  556. Log lines have this form:
  557. Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
  558. where the fields are defined as follows:
  559. L A single character, representing the log level (eg 'I' for INFO)
  560. mm The month (zero padded; ie May is '05')
  561. dd The day (zero padded)
  562. hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
  563. threadid The space-padded thread ID as returned by GetTID()
  564. file The file name
  565. line The line number
  566. msg The user-supplied message
  567. */
  568. func (l *loggingT) header(s severity.Severity, depth int) (*buffer.Buffer, string, int) {
  569. _, file, line, ok := runtime.Caller(3 + depth)
  570. if !ok {
  571. file = "???"
  572. line = 1
  573. } else {
  574. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  575. path := file
  576. file = path[slash+1:]
  577. if l.addDirHeader {
  578. if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 {
  579. file = path[dirsep+1:]
  580. }
  581. }
  582. }
  583. }
  584. return l.formatHeader(s, file, line, timeNow()), file, line
  585. }
  586. // formatHeader formats a log header using the provided file name and line number.
  587. func (l *loggingT) formatHeader(s severity.Severity, file string, line int, now time.Time) *buffer.Buffer {
  588. buf := buffer.GetBuffer()
  589. if l.skipHeaders {
  590. return buf
  591. }
  592. buf.FormatHeader(s, file, line, now)
  593. return buf
  594. }
  595. func (l *loggingT) println(s severity.Severity, logger *logWriter, filter LogFilter, args ...interface{}) {
  596. l.printlnDepth(s, logger, filter, 1, args...)
  597. }
  598. func (l *loggingT) printlnDepth(s severity.Severity, logger *logWriter, filter LogFilter, depth int, args ...interface{}) {
  599. if false {
  600. _ = fmt.Sprintln(args...) // cause vet to treat this function like fmt.Println
  601. }
  602. buf, file, line := l.header(s, depth)
  603. // If a logger is set and doesn't support writing a formatted buffer,
  604. // we clear the generated header as we rely on the backing
  605. // logger implementation to print headers.
  606. if logger != nil && logger.writeKlogBuffer == nil {
  607. buffer.PutBuffer(buf)
  608. buf = buffer.GetBuffer()
  609. }
  610. if filter != nil {
  611. args = filter.Filter(args)
  612. }
  613. fmt.Fprintln(buf, args...)
  614. l.output(s, logger, buf, depth, file, line, false)
  615. }
  616. func (l *loggingT) print(s severity.Severity, logger *logWriter, filter LogFilter, args ...interface{}) {
  617. l.printDepth(s, logger, filter, 1, args...)
  618. }
  619. func (l *loggingT) printDepth(s severity.Severity, logger *logWriter, filter LogFilter, depth int, args ...interface{}) {
  620. if false {
  621. _ = fmt.Sprint(args...) // // cause vet to treat this function like fmt.Print
  622. }
  623. buf, file, line := l.header(s, depth)
  624. l.printWithInfos(buf, file, line, s, logger, filter, depth+1, args...)
  625. }
  626. func (l *loggingT) printWithInfos(buf *buffer.Buffer, file string, line int, s severity.Severity, logger *logWriter, filter LogFilter, depth int, args ...interface{}) {
  627. // If a logger is set and doesn't support writing a formatted buffer,
  628. // we clear the generated header as we rely on the backing
  629. // logger implementation to print headers.
  630. if logger != nil && logger.writeKlogBuffer == nil {
  631. buffer.PutBuffer(buf)
  632. buf = buffer.GetBuffer()
  633. }
  634. if filter != nil {
  635. args = filter.Filter(args)
  636. }
  637. fmt.Fprint(buf, args...)
  638. if buf.Len() == 0 || buf.Bytes()[buf.Len()-1] != '\n' {
  639. buf.WriteByte('\n')
  640. }
  641. l.output(s, logger, buf, depth, file, line, false)
  642. }
  643. func (l *loggingT) printf(s severity.Severity, logger *logWriter, filter LogFilter, format string, args ...interface{}) {
  644. l.printfDepth(s, logger, filter, 1, format, args...)
  645. }
  646. func (l *loggingT) printfDepth(s severity.Severity, logger *logWriter, filter LogFilter, depth int, format string, args ...interface{}) {
  647. if false {
  648. _ = fmt.Sprintf(format, args...) // cause vet to treat this function like fmt.Printf
  649. }
  650. buf, file, line := l.header(s, depth)
  651. // If a logger is set and doesn't support writing a formatted buffer,
  652. // we clear the generated header as we rely on the backing
  653. // logger implementation to print headers.
  654. if logger != nil && logger.writeKlogBuffer == nil {
  655. buffer.PutBuffer(buf)
  656. buf = buffer.GetBuffer()
  657. }
  658. if filter != nil {
  659. format, args = filter.FilterF(format, args)
  660. }
  661. fmt.Fprintf(buf, format, args...)
  662. if buf.Bytes()[buf.Len()-1] != '\n' {
  663. buf.WriteByte('\n')
  664. }
  665. l.output(s, logger, buf, depth, file, line, false)
  666. }
  667. // printWithFileLine behaves like print but uses the provided file and line number. If
  668. // alsoLogToStderr is true, the log message always appears on standard error; it
  669. // will also appear in the log file unless --logtostderr is set.
  670. func (l *loggingT) printWithFileLine(s severity.Severity, logger *logWriter, filter LogFilter, file string, line int, alsoToStderr bool, args ...interface{}) {
  671. buf := l.formatHeader(s, file, line, timeNow())
  672. // If a logger is set and doesn't support writing a formatted buffer,
  673. // we clear the generated header as we rely on the backing
  674. // logger implementation to print headers.
  675. if logger != nil && logger.writeKlogBuffer == nil {
  676. buffer.PutBuffer(buf)
  677. buf = buffer.GetBuffer()
  678. }
  679. if filter != nil {
  680. args = filter.Filter(args)
  681. }
  682. fmt.Fprint(buf, args...)
  683. if buf.Bytes()[buf.Len()-1] != '\n' {
  684. buf.WriteByte('\n')
  685. }
  686. l.output(s, logger, buf, 2 /* depth */, file, line, alsoToStderr)
  687. }
  688. // if logger is specified, will call logger.Error, otherwise output with logging module.
  689. func (l *loggingT) errorS(err error, logger *logWriter, filter LogFilter, depth int, msg string, keysAndValues ...interface{}) {
  690. if filter != nil {
  691. msg, keysAndValues = filter.FilterS(msg, keysAndValues)
  692. }
  693. if logger != nil {
  694. logger.WithCallDepth(depth+2).Error(err, msg, keysAndValues...)
  695. return
  696. }
  697. l.printS(err, severity.ErrorLog, depth+1, msg, keysAndValues...)
  698. }
  699. // if logger is specified, will call logger.Info, otherwise output with logging module.
  700. func (l *loggingT) infoS(logger *logWriter, filter LogFilter, depth int, msg string, keysAndValues ...interface{}) {
  701. if filter != nil {
  702. msg, keysAndValues = filter.FilterS(msg, keysAndValues)
  703. }
  704. if logger != nil {
  705. logger.WithCallDepth(depth+2).Info(msg, keysAndValues...)
  706. return
  707. }
  708. l.printS(nil, severity.InfoLog, depth+1, msg, keysAndValues...)
  709. }
  710. // printS is called from infoS and errorS if logger is not specified.
  711. // set log severity by s
  712. func (l *loggingT) printS(err error, s severity.Severity, depth int, msg string, keysAndValues ...interface{}) {
  713. // Only create a new buffer if we don't have one cached.
  714. b := buffer.GetBuffer()
  715. // The message is always quoted, even if it contains line breaks.
  716. // If developers want multi-line output, they should use a small, fixed
  717. // message and put the multi-line output into a value.
  718. b.WriteString(strconv.Quote(msg))
  719. if err != nil {
  720. serialize.KVListFormat(&b.Buffer, "err", err)
  721. }
  722. serialize.KVListFormat(&b.Buffer, keysAndValues...)
  723. l.printDepth(s, nil, nil, depth+1, &b.Buffer)
  724. // Make the buffer available for reuse.
  725. buffer.PutBuffer(b)
  726. }
  727. // SetOutput sets the output destination for all severities
  728. func SetOutput(w io.Writer) {
  729. logging.mu.Lock()
  730. defer logging.mu.Unlock()
  731. for s := severity.FatalLog; s >= severity.InfoLog; s-- {
  732. logging.file[s] = w
  733. }
  734. }
  735. // SetOutputBySeverity sets the output destination for specific severity
  736. func SetOutputBySeverity(name string, w io.Writer) {
  737. logging.mu.Lock()
  738. defer logging.mu.Unlock()
  739. sev, ok := severity.ByName(name)
  740. if !ok {
  741. panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
  742. }
  743. logging.file[sev] = w
  744. }
  745. // LogToStderr sets whether to log exclusively to stderr, bypassing outputs
  746. func LogToStderr(stderr bool) {
  747. logging.mu.Lock()
  748. defer logging.mu.Unlock()
  749. logging.toStderr = stderr
  750. }
  751. // output writes the data to the log files and releases the buffer.
  752. func (l *loggingT) output(s severity.Severity, logger *logWriter, buf *buffer.Buffer, depth int, file string, line int, alsoToStderr bool) {
  753. var isLocked = true
  754. l.mu.Lock()
  755. defer func() {
  756. if isLocked {
  757. // Unlock before returning in case that it wasn't done already.
  758. l.mu.Unlock()
  759. }
  760. }()
  761. if l.traceLocation.isSet() {
  762. if l.traceLocation.match(file, line) {
  763. buf.Write(dbg.Stacks(false))
  764. }
  765. }
  766. data := buf.Bytes()
  767. if logger != nil {
  768. if logger.writeKlogBuffer != nil {
  769. logger.writeKlogBuffer(data)
  770. } else {
  771. if len(data) > 0 && data[len(data)-1] == '\n' {
  772. data = data[:len(data)-1]
  773. }
  774. // TODO: set 'severity' and caller information as structured log info
  775. // keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line}
  776. if s == severity.ErrorLog {
  777. logger.WithCallDepth(depth+3).Error(nil, string(data))
  778. } else {
  779. logger.WithCallDepth(depth + 3).Info(string(data))
  780. }
  781. }
  782. } else if l.toStderr {
  783. os.Stderr.Write(data)
  784. } else {
  785. if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
  786. os.Stderr.Write(data)
  787. }
  788. if logging.logFile != "" {
  789. // Since we are using a single log file, all of the items in l.file array
  790. // will point to the same file, so just use one of them to write data.
  791. if l.file[severity.InfoLog] == nil {
  792. if err := l.createFiles(severity.InfoLog); err != nil {
  793. os.Stderr.Write(data) // Make sure the message appears somewhere.
  794. l.exit(err)
  795. }
  796. }
  797. _, _ = l.file[severity.InfoLog].Write(data)
  798. } else {
  799. if l.file[s] == nil {
  800. if err := l.createFiles(s); err != nil {
  801. os.Stderr.Write(data) // Make sure the message appears somewhere.
  802. l.exit(err)
  803. }
  804. }
  805. if l.oneOutput {
  806. _, _ = l.file[s].Write(data)
  807. } else {
  808. switch s {
  809. case severity.FatalLog:
  810. _, _ = l.file[severity.FatalLog].Write(data)
  811. fallthrough
  812. case severity.ErrorLog:
  813. _, _ = l.file[severity.ErrorLog].Write(data)
  814. fallthrough
  815. case severity.WarningLog:
  816. _, _ = l.file[severity.WarningLog].Write(data)
  817. fallthrough
  818. case severity.InfoLog:
  819. _, _ = l.file[severity.InfoLog].Write(data)
  820. }
  821. }
  822. }
  823. }
  824. if s == severity.FatalLog {
  825. // If we got here via Exit rather than Fatal, print no stacks.
  826. if atomic.LoadUint32(&fatalNoStacks) > 0 {
  827. l.mu.Unlock()
  828. isLocked = false
  829. timeoutFlush(ExitFlushTimeout)
  830. OsExit(1)
  831. }
  832. // Dump all goroutine stacks before exiting.
  833. // First, make sure we see the trace for the current goroutine on standard error.
  834. // If -logtostderr has been specified, the loop below will do that anyway
  835. // as the first stack in the full dump.
  836. if !l.toStderr {
  837. os.Stderr.Write(dbg.Stacks(false))
  838. }
  839. // Write the stack trace for all goroutines to the files.
  840. trace := dbg.Stacks(true)
  841. logExitFunc = func(error) {} // If we get a write error, we'll still exit below.
  842. for log := severity.FatalLog; log >= severity.InfoLog; log-- {
  843. if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.
  844. _, _ = f.Write(trace)
  845. }
  846. }
  847. l.mu.Unlock()
  848. isLocked = false
  849. timeoutFlush(ExitFlushTimeout)
  850. OsExit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.
  851. }
  852. buffer.PutBuffer(buf)
  853. if stats := severityStats[s]; stats != nil {
  854. atomic.AddInt64(&stats.lines, 1)
  855. atomic.AddInt64(&stats.bytes, int64(len(data)))
  856. }
  857. }
  858. // logExitFunc provides a simple mechanism to override the default behavior
  859. // of exiting on error. Used in testing and to guarantee we reach a required exit
  860. // for fatal logs. Instead, exit could be a function rather than a method but that
  861. // would make its use clumsier.
  862. var logExitFunc func(error)
  863. // exit is called if there is trouble creating or writing log files.
  864. // It flushes the logs and exits the program; there's no point in hanging around.
  865. // l.mu is held.
  866. func (l *loggingT) exit(err error) {
  867. fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err)
  868. // If logExitFunc is set, we do that instead of exiting.
  869. if logExitFunc != nil {
  870. logExitFunc(err)
  871. return
  872. }
  873. needToSync := l.flushAll()
  874. l.syncAll(needToSync)
  875. OsExit(2)
  876. }
  877. // syncBuffer joins a bufio.Writer to its underlying file, providing access to the
  878. // file's Sync method and providing a wrapper for the Write method that provides log
  879. // file rotation. There are conflicting methods, so the file cannot be embedded.
  880. // l.mu is held for all its methods.
  881. type syncBuffer struct {
  882. logger *loggingT
  883. *bufio.Writer
  884. file *os.File
  885. sev severity.Severity
  886. nbytes uint64 // The number of bytes written to this file
  887. maxbytes uint64 // The max number of bytes this syncBuffer.file can hold before cleaning up.
  888. }
  889. // CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options.
  890. func CalculateMaxSize() uint64 {
  891. if logging.logFile != "" {
  892. if logging.logFileMaxSizeMB == 0 {
  893. // If logFileMaxSizeMB is zero, we don't have limitations on the log size.
  894. return math.MaxUint64
  895. }
  896. // Flag logFileMaxSizeMB is in MB for user convenience.
  897. return logging.logFileMaxSizeMB * 1024 * 1024
  898. }
  899. // If "log_file" flag is not specified, the target file (sb.file) will be cleaned up when reaches a fixed size.
  900. return MaxSize
  901. }
  902. func (sb *syncBuffer) Write(p []byte) (n int, err error) {
  903. if sb.nbytes+uint64(len(p)) >= sb.maxbytes {
  904. if err := sb.rotateFile(time.Now(), false); err != nil {
  905. sb.logger.exit(err)
  906. }
  907. }
  908. n, err = sb.Writer.Write(p)
  909. sb.nbytes += uint64(n)
  910. if err != nil {
  911. sb.logger.exit(err)
  912. }
  913. return
  914. }
  915. // rotateFile closes the syncBuffer's file and starts a new one.
  916. // The startup argument indicates whether this is the initial startup of klog.
  917. // If startup is true, existing files are opened for appending instead of truncated.
  918. func (sb *syncBuffer) rotateFile(now time.Time, startup bool) error {
  919. if sb.file != nil {
  920. sb.Flush()
  921. sb.file.Close()
  922. }
  923. var err error
  924. sb.file, _, err = create(severity.Name[sb.sev], now, startup)
  925. if err != nil {
  926. return err
  927. }
  928. if startup {
  929. fileInfo, err := sb.file.Stat()
  930. if err != nil {
  931. return fmt.Errorf("file stat could not get fileinfo: %v", err)
  932. }
  933. // init file size
  934. sb.nbytes = uint64(fileInfo.Size())
  935. } else {
  936. sb.nbytes = 0
  937. }
  938. sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
  939. if sb.logger.skipLogHeaders {
  940. return nil
  941. }
  942. // Write header.
  943. var buf bytes.Buffer
  944. fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
  945. fmt.Fprintf(&buf, "Running on machine: %s\n", host)
  946. fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
  947. fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n")
  948. n, err := sb.file.Write(buf.Bytes())
  949. sb.nbytes += uint64(n)
  950. return err
  951. }
  952. // bufferSize sizes the buffer associated with each log file. It's large
  953. // so that log records can accumulate without the logging thread blocking
  954. // on disk I/O. The flushDaemon will block instead.
  955. const bufferSize = 256 * 1024
  956. // createFiles creates all the log files for severity from sev down to infoLog.
  957. // l.mu is held.
  958. func (l *loggingT) createFiles(sev severity.Severity) error {
  959. interval := l.flushInterval
  960. if interval == 0 {
  961. interval = flushInterval
  962. }
  963. l.flushD.run(interval)
  964. now := time.Now()
  965. // Files are created in decreasing severity order, so as soon as we find one
  966. // has already been created, we can stop.
  967. for s := sev; s >= severity.InfoLog && l.file[s] == nil; s-- {
  968. sb := &syncBuffer{
  969. logger: l,
  970. sev: s,
  971. maxbytes: CalculateMaxSize(),
  972. }
  973. if err := sb.rotateFile(now, true); err != nil {
  974. return err
  975. }
  976. l.file[s] = sb
  977. }
  978. return nil
  979. }
  980. const flushInterval = 5 * time.Second
  981. // flushDaemon periodically flushes the log file buffers.
  982. type flushDaemon struct {
  983. mu sync.Mutex
  984. clock clock.Clock
  985. flush func()
  986. stopC chan struct{}
  987. stopDone chan struct{}
  988. }
  989. // newFlushDaemon returns a new flushDaemon. If the passed clock is nil, a
  990. // clock.RealClock is used.
  991. func newFlushDaemon(flush func(), tickClock clock.Clock) *flushDaemon {
  992. if tickClock == nil {
  993. tickClock = clock.RealClock{}
  994. }
  995. return &flushDaemon{
  996. flush: flush,
  997. clock: tickClock,
  998. }
  999. }
  1000. // run starts a goroutine that periodically calls the daemons flush function.
  1001. // Calling run on an already running daemon will have no effect.
  1002. func (f *flushDaemon) run(interval time.Duration) {
  1003. f.mu.Lock()
  1004. defer f.mu.Unlock()
  1005. if f.stopC != nil { // daemon already running
  1006. return
  1007. }
  1008. f.stopC = make(chan struct{}, 1)
  1009. f.stopDone = make(chan struct{}, 1)
  1010. ticker := f.clock.NewTicker(interval)
  1011. go func() {
  1012. defer ticker.Stop()
  1013. defer func() { f.stopDone <- struct{}{} }()
  1014. for {
  1015. select {
  1016. case <-ticker.C():
  1017. f.flush()
  1018. case <-f.stopC:
  1019. f.flush()
  1020. return
  1021. }
  1022. }
  1023. }()
  1024. }
  1025. // stop stops the running flushDaemon and waits until the daemon has shut down.
  1026. // Calling stop on a daemon that isn't running will have no effect.
  1027. func (f *flushDaemon) stop() {
  1028. f.mu.Lock()
  1029. defer f.mu.Unlock()
  1030. if f.stopC == nil { // daemon not running
  1031. return
  1032. }
  1033. f.stopC <- struct{}{}
  1034. <-f.stopDone
  1035. f.stopC = nil
  1036. f.stopDone = nil
  1037. }
  1038. // isRunning returns true if the flush daemon is running.
  1039. func (f *flushDaemon) isRunning() bool {
  1040. f.mu.Lock()
  1041. defer f.mu.Unlock()
  1042. return f.stopC != nil
  1043. }
  1044. // StopFlushDaemon stops the flush daemon, if running, and flushes once.
  1045. // This prevents klog from leaking goroutines on shutdown. After stopping
  1046. // the daemon, you can still manually flush buffers again by calling Flush().
  1047. func StopFlushDaemon() {
  1048. logging.flushD.stop()
  1049. }
  1050. // StartFlushDaemon ensures that the flush daemon runs with the given delay
  1051. // between flush calls. If it is already running, it gets restarted.
  1052. func StartFlushDaemon(interval time.Duration) {
  1053. StopFlushDaemon()
  1054. logging.flushD.run(interval)
  1055. }
  1056. // lockAndFlushAll is like flushAll but locks l.mu first.
  1057. func (l *loggingT) lockAndFlushAll() {
  1058. l.mu.Lock()
  1059. needToSync := l.flushAll()
  1060. l.mu.Unlock()
  1061. // Some environments are slow when syncing and holding the lock might cause contention.
  1062. l.syncAll(needToSync)
  1063. }
  1064. // flushAll flushes all the logs
  1065. // l.mu is held.
  1066. //
  1067. // The result is the number of files which need to be synced and the pointers to them.
  1068. func (l *loggingT) flushAll() fileArray {
  1069. var needToSync fileArray
  1070. // Flush from fatal down, in case there's trouble flushing.
  1071. for s := severity.FatalLog; s >= severity.InfoLog; s-- {
  1072. file := l.file[s]
  1073. if sb, ok := file.(*syncBuffer); ok && sb.file != nil {
  1074. _ = sb.Flush() // ignore error
  1075. needToSync.files[needToSync.num] = sb.file
  1076. needToSync.num++
  1077. }
  1078. }
  1079. if logging.loggerOptions.flush != nil {
  1080. logging.loggerOptions.flush()
  1081. }
  1082. return needToSync
  1083. }
  1084. type fileArray struct {
  1085. num int
  1086. files [severity.NumSeverity]*os.File
  1087. }
  1088. // syncAll attempts to "sync" their data to disk.
  1089. func (l *loggingT) syncAll(needToSync fileArray) {
  1090. // Flush from fatal down, in case there's trouble flushing.
  1091. for i := 0; i < needToSync.num; i++ {
  1092. _ = needToSync.files[i].Sync() // ignore error
  1093. }
  1094. }
  1095. // CopyStandardLogTo arranges for messages written to the Go "log" package's
  1096. // default logs to also appear in the Google logs for the named and lower
  1097. // severities. Subsequent changes to the standard log's default output location
  1098. // or format may break this behavior.
  1099. //
  1100. // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
  1101. // recognized, CopyStandardLogTo panics.
  1102. func CopyStandardLogTo(name string) {
  1103. sev, ok := severity.ByName(name)
  1104. if !ok {
  1105. panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
  1106. }
  1107. // Set a log format that captures the user's file and line:
  1108. // d.go:23: message
  1109. stdLog.SetFlags(stdLog.Lshortfile)
  1110. stdLog.SetOutput(logBridge(sev))
  1111. }
  1112. // NewStandardLogger returns a Logger that writes to the klog logs for the
  1113. // named and lower severities.
  1114. //
  1115. // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
  1116. // recognized, NewStandardLogger panics.
  1117. func NewStandardLogger(name string) *stdLog.Logger {
  1118. sev, ok := severity.ByName(name)
  1119. if !ok {
  1120. panic(fmt.Sprintf("klog.NewStandardLogger(%q): unknown severity", name))
  1121. }
  1122. return stdLog.New(logBridge(sev), "", stdLog.Lshortfile)
  1123. }
  1124. // logBridge provides the Write method that enables CopyStandardLogTo to connect
  1125. // Go's standard logs to the logs provided by this package.
  1126. type logBridge severity.Severity
  1127. // Write parses the standard logging line and passes its components to the
  1128. // logger for severity(lb).
  1129. func (lb logBridge) Write(b []byte) (n int, err error) {
  1130. var (
  1131. file = "???"
  1132. line = 1
  1133. text string
  1134. )
  1135. // Split "d.go:23: message" into "d.go", "23", and "message".
  1136. if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
  1137. text = fmt.Sprintf("bad log format: %s", b)
  1138. } else {
  1139. file = string(parts[0])
  1140. text = string(parts[2][1:]) // skip leading space
  1141. line, err = strconv.Atoi(string(parts[1]))
  1142. if err != nil {
  1143. text = fmt.Sprintf("bad line number: %s", b)
  1144. line = 1
  1145. }
  1146. }
  1147. // printWithFileLine with alsoToStderr=true, so standard log messages
  1148. // always appear on standard error.
  1149. logging.printWithFileLine(severity.Severity(lb), logging.logger, logging.filter, file, line, true, text)
  1150. return len(b), nil
  1151. }
  1152. // setV computes and remembers the V level for a given PC
  1153. // when vmodule is enabled.
  1154. // File pattern matching takes the basename of the file, stripped
  1155. // of its .go suffix, and uses filepath.Match, which is a little more
  1156. // general than the *? matching used in C++.
  1157. // l.mu is held.
  1158. func (l *loggingT) setV(pc uintptr) Level {
  1159. fn := runtime.FuncForPC(pc)
  1160. file, _ := fn.FileLine(pc)
  1161. // The file is something like /a/b/c/d.go. We want just the d.
  1162. file = strings.TrimSuffix(file, ".go")
  1163. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  1164. file = file[slash+1:]
  1165. }
  1166. for _, filter := range l.vmodule.filter {
  1167. if filter.match(file) {
  1168. l.vmap[pc] = filter.level
  1169. return filter.level
  1170. }
  1171. }
  1172. l.vmap[pc] = 0
  1173. return 0
  1174. }
  1175. // Verbose is a boolean type that implements Infof (like Printf) etc.
  1176. // See the documentation of V for more information.
  1177. type Verbose struct {
  1178. enabled bool
  1179. logger *logWriter
  1180. }
  1181. func newVerbose(level Level, b bool) Verbose {
  1182. if logging.logger == nil {
  1183. return Verbose{b, nil}
  1184. }
  1185. v := logging.logger.V(int(level))
  1186. return Verbose{b, &logWriter{Logger: v, writeKlogBuffer: logging.loggerOptions.writeKlogBuffer}}
  1187. }
  1188. // V reports whether verbosity at the call site is at least the requested level.
  1189. // The returned value is a struct of type Verbose, which implements Info, Infoln
  1190. // and Infof. These methods will write to the Info log if called.
  1191. // Thus, one may write either
  1192. //
  1193. // if klog.V(2).Enabled() { klog.Info("log this") }
  1194. //
  1195. // or
  1196. //
  1197. // klog.V(2).Info("log this")
  1198. //
  1199. // The second form is shorter but the first is cheaper if logging is off because it does
  1200. // not evaluate its arguments.
  1201. //
  1202. // Whether an individual call to V generates a log record depends on the setting of
  1203. // the -v and -vmodule flags; both are off by default. The V call will log if its level
  1204. // is less than or equal to the value of the -v flag, or alternatively if its level is
  1205. // less than or equal to the value of the -vmodule pattern matching the source file
  1206. // containing the call.
  1207. func V(level Level) Verbose {
  1208. return VDepth(1, level)
  1209. }
  1210. // VDepth is a variant of V that accepts a number of stack frames that will be
  1211. // skipped when checking the -vmodule patterns. VDepth(0) is equivalent to
  1212. // V().
  1213. func VDepth(depth int, level Level) Verbose {
  1214. // This function tries hard to be cheap unless there's work to do.
  1215. // The fast path is two atomic loads and compares.
  1216. // Here is a cheap but safe test to see if V logging is enabled globally.
  1217. if logging.verbosity.get() >= level {
  1218. return newVerbose(level, true)
  1219. }
  1220. // It's off globally but vmodule may still be set.
  1221. // Here is another cheap but safe test to see if vmodule is enabled.
  1222. if atomic.LoadInt32(&logging.filterLength) > 0 {
  1223. // Now we need a proper lock to use the logging structure. The pcs field
  1224. // is shared so we must lock before accessing it. This is fairly expensive,
  1225. // but if V logging is enabled we're slow anyway.
  1226. logging.mu.Lock()
  1227. defer logging.mu.Unlock()
  1228. if runtime.Callers(2+depth, logging.pcs[:]) == 0 {
  1229. return newVerbose(level, false)
  1230. }
  1231. // runtime.Callers returns "return PCs", but we want
  1232. // to look up the symbolic information for the call,
  1233. // so subtract 1 from the PC. runtime.CallersFrames
  1234. // would be cleaner, but allocates.
  1235. pc := logging.pcs[0] - 1
  1236. v, ok := logging.vmap[pc]
  1237. if !ok {
  1238. v = logging.setV(pc)
  1239. }
  1240. return newVerbose(level, v >= level)
  1241. }
  1242. return newVerbose(level, false)
  1243. }
  1244. // Enabled will return true if this log level is enabled, guarded by the value
  1245. // of v.
  1246. // See the documentation of V for usage.
  1247. func (v Verbose) Enabled() bool {
  1248. return v.enabled
  1249. }
  1250. // Info is equivalent to the global Info function, guarded by the value of v.
  1251. // See the documentation of V for usage.
  1252. func (v Verbose) Info(args ...interface{}) {
  1253. if v.enabled {
  1254. logging.print(severity.InfoLog, v.logger, logging.filter, args...)
  1255. }
  1256. }
  1257. // InfoDepth is equivalent to the global InfoDepth function, guarded by the value of v.
  1258. // See the documentation of V for usage.
  1259. func (v Verbose) InfoDepth(depth int, args ...interface{}) {
  1260. if v.enabled {
  1261. logging.printDepth(severity.InfoLog, v.logger, logging.filter, depth, args...)
  1262. }
  1263. }
  1264. // Infoln is equivalent to the global Infoln function, guarded by the value of v.
  1265. // See the documentation of V for usage.
  1266. func (v Verbose) Infoln(args ...interface{}) {
  1267. if v.enabled {
  1268. logging.println(severity.InfoLog, v.logger, logging.filter, args...)
  1269. }
  1270. }
  1271. // InfolnDepth is equivalent to the global InfolnDepth function, guarded by the value of v.
  1272. // See the documentation of V for usage.
  1273. func (v Verbose) InfolnDepth(depth int, args ...interface{}) {
  1274. if v.enabled {
  1275. logging.printlnDepth(severity.InfoLog, v.logger, logging.filter, depth, args...)
  1276. }
  1277. }
  1278. // Infof is equivalent to the global Infof function, guarded by the value of v.
  1279. // See the documentation of V for usage.
  1280. func (v Verbose) Infof(format string, args ...interface{}) {
  1281. if v.enabled {
  1282. logging.printf(severity.InfoLog, v.logger, logging.filter, format, args...)
  1283. }
  1284. }
  1285. // InfofDepth is equivalent to the global InfofDepth function, guarded by the value of v.
  1286. // See the documentation of V for usage.
  1287. func (v Verbose) InfofDepth(depth int, format string, args ...interface{}) {
  1288. if v.enabled {
  1289. logging.printfDepth(severity.InfoLog, v.logger, logging.filter, depth, format, args...)
  1290. }
  1291. }
  1292. // InfoS is equivalent to the global InfoS function, guarded by the value of v.
  1293. // See the documentation of V for usage.
  1294. func (v Verbose) InfoS(msg string, keysAndValues ...interface{}) {
  1295. if v.enabled {
  1296. logging.infoS(v.logger, logging.filter, 0, msg, keysAndValues...)
  1297. }
  1298. }
  1299. // InfoSDepth acts as InfoS but uses depth to determine which call frame to log.
  1300. // InfoSDepth(0, "msg") is the same as InfoS("msg").
  1301. func InfoSDepth(depth int, msg string, keysAndValues ...interface{}) {
  1302. logging.infoS(logging.logger, logging.filter, depth, msg, keysAndValues...)
  1303. }
  1304. // InfoSDepth is equivalent to the global InfoSDepth function, guarded by the value of v.
  1305. // See the documentation of V for usage.
  1306. func (v Verbose) InfoSDepth(depth int, msg string, keysAndValues ...interface{}) {
  1307. if v.enabled {
  1308. logging.infoS(v.logger, logging.filter, depth, msg, keysAndValues...)
  1309. }
  1310. }
  1311. // Deprecated: Use ErrorS instead.
  1312. func (v Verbose) Error(err error, msg string, args ...interface{}) {
  1313. if v.enabled {
  1314. logging.errorS(err, v.logger, logging.filter, 0, msg, args...)
  1315. }
  1316. }
  1317. // ErrorS is equivalent to the global Error function, guarded by the value of v.
  1318. // See the documentation of V for usage.
  1319. func (v Verbose) ErrorS(err error, msg string, keysAndValues ...interface{}) {
  1320. if v.enabled {
  1321. logging.errorS(err, v.logger, logging.filter, 0, msg, keysAndValues...)
  1322. }
  1323. }
  1324. // Info logs to the INFO log.
  1325. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1326. func Info(args ...interface{}) {
  1327. logging.print(severity.InfoLog, logging.logger, logging.filter, args...)
  1328. }
  1329. // InfoDepth acts as Info but uses depth to determine which call frame to log.
  1330. // InfoDepth(0, "msg") is the same as Info("msg").
  1331. func InfoDepth(depth int, args ...interface{}) {
  1332. logging.printDepth(severity.InfoLog, logging.logger, logging.filter, depth, args...)
  1333. }
  1334. // Infoln logs to the INFO log.
  1335. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1336. func Infoln(args ...interface{}) {
  1337. logging.println(severity.InfoLog, logging.logger, logging.filter, args...)
  1338. }
  1339. // InfolnDepth acts as Infoln but uses depth to determine which call frame to log.
  1340. // InfolnDepth(0, "msg") is the same as Infoln("msg").
  1341. func InfolnDepth(depth int, args ...interface{}) {
  1342. logging.printlnDepth(severity.InfoLog, logging.logger, logging.filter, depth, args...)
  1343. }
  1344. // Infof logs to the INFO log.
  1345. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1346. func Infof(format string, args ...interface{}) {
  1347. logging.printf(severity.InfoLog, logging.logger, logging.filter, format, args...)
  1348. }
  1349. // InfofDepth acts as Infof but uses depth to determine which call frame to log.
  1350. // InfofDepth(0, "msg", args...) is the same as Infof("msg", args...).
  1351. func InfofDepth(depth int, format string, args ...interface{}) {
  1352. logging.printfDepth(severity.InfoLog, logging.logger, logging.filter, depth, format, args...)
  1353. }
  1354. // InfoS structured logs to the INFO log.
  1355. // The msg argument used to add constant description to the log line.
  1356. // The key/value pairs would be join by "=" ; a newline is always appended.
  1357. //
  1358. // Basic examples:
  1359. // >> klog.InfoS("Pod status updated", "pod", "kubedns", "status", "ready")
  1360. // output:
  1361. // >> I1025 00:15:15.525108 1 controller_utils.go:116] "Pod status updated" pod="kubedns" status="ready"
  1362. func InfoS(msg string, keysAndValues ...interface{}) {
  1363. logging.infoS(logging.logger, logging.filter, 0, msg, keysAndValues...)
  1364. }
  1365. // Warning logs to the WARNING and INFO logs.
  1366. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1367. func Warning(args ...interface{}) {
  1368. logging.print(severity.WarningLog, logging.logger, logging.filter, args...)
  1369. }
  1370. // WarningDepth acts as Warning but uses depth to determine which call frame to log.
  1371. // WarningDepth(0, "msg") is the same as Warning("msg").
  1372. func WarningDepth(depth int, args ...interface{}) {
  1373. logging.printDepth(severity.WarningLog, logging.logger, logging.filter, depth, args...)
  1374. }
  1375. // Warningln logs to the WARNING and INFO logs.
  1376. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1377. func Warningln(args ...interface{}) {
  1378. logging.println(severity.WarningLog, logging.logger, logging.filter, args...)
  1379. }
  1380. // WarninglnDepth acts as Warningln but uses depth to determine which call frame to log.
  1381. // WarninglnDepth(0, "msg") is the same as Warningln("msg").
  1382. func WarninglnDepth(depth int, args ...interface{}) {
  1383. logging.printlnDepth(severity.WarningLog, logging.logger, logging.filter, depth, args...)
  1384. }
  1385. // Warningf logs to the WARNING and INFO logs.
  1386. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1387. func Warningf(format string, args ...interface{}) {
  1388. logging.printf(severity.WarningLog, logging.logger, logging.filter, format, args...)
  1389. }
  1390. // WarningfDepth acts as Warningf but uses depth to determine which call frame to log.
  1391. // WarningfDepth(0, "msg", args...) is the same as Warningf("msg", args...).
  1392. func WarningfDepth(depth int, format string, args ...interface{}) {
  1393. logging.printfDepth(severity.WarningLog, logging.logger, logging.filter, depth, format, args...)
  1394. }
  1395. // Error logs to the ERROR, WARNING, and INFO logs.
  1396. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1397. func Error(args ...interface{}) {
  1398. logging.print(severity.ErrorLog, logging.logger, logging.filter, args...)
  1399. }
  1400. // ErrorDepth acts as Error but uses depth to determine which call frame to log.
  1401. // ErrorDepth(0, "msg") is the same as Error("msg").
  1402. func ErrorDepth(depth int, args ...interface{}) {
  1403. logging.printDepth(severity.ErrorLog, logging.logger, logging.filter, depth, args...)
  1404. }
  1405. // Errorln logs to the ERROR, WARNING, and INFO logs.
  1406. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1407. func Errorln(args ...interface{}) {
  1408. logging.println(severity.ErrorLog, logging.logger, logging.filter, args...)
  1409. }
  1410. // ErrorlnDepth acts as Errorln but uses depth to determine which call frame to log.
  1411. // ErrorlnDepth(0, "msg") is the same as Errorln("msg").
  1412. func ErrorlnDepth(depth int, args ...interface{}) {
  1413. logging.printlnDepth(severity.ErrorLog, logging.logger, logging.filter, depth, args...)
  1414. }
  1415. // Errorf logs to the ERROR, WARNING, and INFO logs.
  1416. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1417. func Errorf(format string, args ...interface{}) {
  1418. logging.printf(severity.ErrorLog, logging.logger, logging.filter, format, args...)
  1419. }
  1420. // ErrorfDepth acts as Errorf but uses depth to determine which call frame to log.
  1421. // ErrorfDepth(0, "msg", args...) is the same as Errorf("msg", args...).
  1422. func ErrorfDepth(depth int, format string, args ...interface{}) {
  1423. logging.printfDepth(severity.ErrorLog, logging.logger, logging.filter, depth, format, args...)
  1424. }
  1425. // ErrorS structured logs to the ERROR, WARNING, and INFO logs.
  1426. // the err argument used as "err" field of log line.
  1427. // The msg argument used to add constant description to the log line.
  1428. // The key/value pairs would be join by "=" ; a newline is always appended.
  1429. //
  1430. // Basic examples:
  1431. // >> klog.ErrorS(err, "Failed to update pod status")
  1432. // output:
  1433. // >> E1025 00:15:15.525108 1 controller_utils.go:114] "Failed to update pod status" err="timeout"
  1434. func ErrorS(err error, msg string, keysAndValues ...interface{}) {
  1435. logging.errorS(err, logging.logger, logging.filter, 0, msg, keysAndValues...)
  1436. }
  1437. // ErrorSDepth acts as ErrorS but uses depth to determine which call frame to log.
  1438. // ErrorSDepth(0, "msg") is the same as ErrorS("msg").
  1439. func ErrorSDepth(depth int, err error, msg string, keysAndValues ...interface{}) {
  1440. logging.errorS(err, logging.logger, logging.filter, depth, msg, keysAndValues...)
  1441. }
  1442. // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
  1443. // prints stack trace(s), then calls OsExit(255).
  1444. //
  1445. // Stderr only receives a dump of the current goroutine's stack trace. Log files,
  1446. // if there are any, receive a dump of the stack traces in all goroutines.
  1447. //
  1448. // Callers who want more control over handling of fatal events may instead use a
  1449. // combination of different functions:
  1450. // - some info or error logging function, optionally with a stack trace
  1451. // value generated by github.com/go-logr/lib/dbg.Backtrace
  1452. // - Flush to flush pending log data
  1453. // - panic, os.Exit or returning to the caller with an error
  1454. //
  1455. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1456. func Fatal(args ...interface{}) {
  1457. logging.print(severity.FatalLog, logging.logger, logging.filter, args...)
  1458. }
  1459. // FatalDepth acts as Fatal but uses depth to determine which call frame to log.
  1460. // FatalDepth(0, "msg") is the same as Fatal("msg").
  1461. func FatalDepth(depth int, args ...interface{}) {
  1462. logging.printDepth(severity.FatalLog, logging.logger, logging.filter, depth, args...)
  1463. }
  1464. // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
  1465. // including a stack trace of all running goroutines, then calls OsExit(255).
  1466. // Arguments are handled in the manner of fmt.Println; a newline is always appended.
  1467. func Fatalln(args ...interface{}) {
  1468. logging.println(severity.FatalLog, logging.logger, logging.filter, args...)
  1469. }
  1470. // FatallnDepth acts as Fatalln but uses depth to determine which call frame to log.
  1471. // FatallnDepth(0, "msg") is the same as Fatalln("msg").
  1472. func FatallnDepth(depth int, args ...interface{}) {
  1473. logging.printlnDepth(severity.FatalLog, logging.logger, logging.filter, depth, args...)
  1474. }
  1475. // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs,
  1476. // including a stack trace of all running goroutines, then calls OsExit(255).
  1477. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1478. func Fatalf(format string, args ...interface{}) {
  1479. logging.printf(severity.FatalLog, logging.logger, logging.filter, format, args...)
  1480. }
  1481. // FatalfDepth acts as Fatalf but uses depth to determine which call frame to log.
  1482. // FatalfDepth(0, "msg", args...) is the same as Fatalf("msg", args...).
  1483. func FatalfDepth(depth int, format string, args ...interface{}) {
  1484. logging.printfDepth(severity.FatalLog, logging.logger, logging.filter, depth, format, args...)
  1485. }
  1486. // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks.
  1487. // It allows Exit and relatives to use the Fatal logs.
  1488. var fatalNoStacks uint32
  1489. // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1).
  1490. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1491. func Exit(args ...interface{}) {
  1492. atomic.StoreUint32(&fatalNoStacks, 1)
  1493. logging.print(severity.FatalLog, logging.logger, logging.filter, args...)
  1494. }
  1495. // ExitDepth acts as Exit but uses depth to determine which call frame to log.
  1496. // ExitDepth(0, "msg") is the same as Exit("msg").
  1497. func ExitDepth(depth int, args ...interface{}) {
  1498. atomic.StoreUint32(&fatalNoStacks, 1)
  1499. logging.printDepth(severity.FatalLog, logging.logger, logging.filter, depth, args...)
  1500. }
  1501. // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1).
  1502. func Exitln(args ...interface{}) {
  1503. atomic.StoreUint32(&fatalNoStacks, 1)
  1504. logging.println(severity.FatalLog, logging.logger, logging.filter, args...)
  1505. }
  1506. // ExitlnDepth acts as Exitln but uses depth to determine which call frame to log.
  1507. // ExitlnDepth(0, "msg") is the same as Exitln("msg").
  1508. func ExitlnDepth(depth int, args ...interface{}) {
  1509. atomic.StoreUint32(&fatalNoStacks, 1)
  1510. logging.printlnDepth(severity.FatalLog, logging.logger, logging.filter, depth, args...)
  1511. }
  1512. // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1).
  1513. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1514. func Exitf(format string, args ...interface{}) {
  1515. atomic.StoreUint32(&fatalNoStacks, 1)
  1516. logging.printf(severity.FatalLog, logging.logger, logging.filter, format, args...)
  1517. }
  1518. // ExitfDepth acts as Exitf but uses depth to determine which call frame to log.
  1519. // ExitfDepth(0, "msg", args...) is the same as Exitf("msg", args...).
  1520. func ExitfDepth(depth int, format string, args ...interface{}) {
  1521. atomic.StoreUint32(&fatalNoStacks, 1)
  1522. logging.printfDepth(severity.FatalLog, logging.logger, logging.filter, depth, format, args...)
  1523. }
  1524. // LogFilter is a collection of functions that can filter all logging calls,
  1525. // e.g. for sanitization of arguments and prevent accidental leaking of secrets.
  1526. type LogFilter interface {
  1527. Filter(args []interface{}) []interface{}
  1528. FilterF(format string, args []interface{}) (string, []interface{})
  1529. FilterS(msg string, keysAndValues []interface{}) (string, []interface{})
  1530. }
  1531. // SetLogFilter installs a filter that is used for all log calls.
  1532. //
  1533. // Modifying the filter is not thread-safe and should be done while no other
  1534. // goroutines invoke log calls, usually during program initialization.
  1535. func SetLogFilter(filter LogFilter) {
  1536. logging.filter = filter
  1537. }