klog.go 40 KB

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