glog.go 36 KB

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