glog.go 35 KB

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