You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1180 lines
36 KiB

  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. // -logdir=""
  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. flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
  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", true, "log to standard error as well as files")
  359. flag.Var(&logging.verbosity, "v", "log levels [0|1|2|3|4], default to 0")
  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. // added by seaweedfs
  408. exited bool
  409. }
  410. // buffer holds a byte Buffer for reuse. The zero value is ready for use.
  411. type buffer struct {
  412. bytes.Buffer
  413. tmp [64]byte // temporary byte array for creating headers.
  414. next *buffer
  415. }
  416. var logging loggingT
  417. // setVState sets a consistent state for V logging.
  418. // l.mu is held.
  419. func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) {
  420. // Turn verbosity off so V will not fire while we are in transition.
  421. logging.verbosity.set(0)
  422. // Ditto for filter length.
  423. atomic.StoreInt32(&logging.filterLength, 0)
  424. // Set the new filters and wipe the pc->Level map if the filter has changed.
  425. if setFilter {
  426. logging.vmodule.filter = filter
  427. logging.vmap = make(map[uintptr]Level)
  428. }
  429. // Things are consistent now, so enable filtering and verbosity.
  430. // They are enabled in order opposite to that in V.
  431. atomic.StoreInt32(&logging.filterLength, int32(len(filter)))
  432. logging.verbosity.set(verbosity)
  433. }
  434. // getBuffer returns a new, ready-to-use buffer.
  435. func (l *loggingT) getBuffer() *buffer {
  436. l.freeListMu.Lock()
  437. b := l.freeList
  438. if b != nil {
  439. l.freeList = b.next
  440. }
  441. l.freeListMu.Unlock()
  442. if b == nil {
  443. b = new(buffer)
  444. } else {
  445. b.next = nil
  446. b.Reset()
  447. }
  448. return b
  449. }
  450. // putBuffer returns a buffer to the free list.
  451. func (l *loggingT) putBuffer(b *buffer) {
  452. if b.Len() >= 256 {
  453. // Let big buffers die a natural death.
  454. return
  455. }
  456. l.freeListMu.Lock()
  457. b.next = l.freeList
  458. l.freeList = b
  459. l.freeListMu.Unlock()
  460. }
  461. var timeNow = time.Now // Stubbed out for testing.
  462. /*
  463. header formats a log header as defined by the C++ implementation.
  464. It returns a buffer containing the formatted header and the user's file and line number.
  465. The depth specifies how many stack frames above lives the source line to be identified in the log message.
  466. Log lines have this form:
  467. Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
  468. where the fields are defined as follows:
  469. L A single character, representing the log level (eg 'I' for INFO)
  470. mm The month (zero padded; ie May is '05')
  471. dd The day (zero padded)
  472. hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
  473. threadid The space-padded thread ID as returned by GetTID()
  474. file The file name
  475. line The line number
  476. msg The user-supplied message
  477. */
  478. func (l *loggingT) header(s severity, depth int) (*buffer, string, int) {
  479. _, file, line, ok := runtime.Caller(3 + depth)
  480. if !ok {
  481. file = "???"
  482. line = 1
  483. } else {
  484. slash := strings.LastIndex(file, "/")
  485. if slash >= 0 {
  486. file = file[slash+1:]
  487. }
  488. }
  489. return l.formatHeader(s, file, line), file, line
  490. }
  491. // formatHeader formats a log header using the provided file name and line number.
  492. func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
  493. now := timeNow()
  494. if line < 0 {
  495. line = 0 // not a real line number, but acceptable to someDigits
  496. }
  497. if s > fatalLog {
  498. s = infoLog // for safety.
  499. }
  500. buf := l.getBuffer()
  501. // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
  502. // It's worth about 3X. Fprintf is hard.
  503. _, month, day := now.Date()
  504. hour, minute, second := now.Clock()
  505. // Lmmdd hh:mm:ss.uuuuuu threadid file:line]
  506. buf.tmp[0] = severityChar[s]
  507. buf.twoDigits(1, int(month))
  508. buf.twoDigits(3, day)
  509. buf.tmp[5] = ' '
  510. buf.twoDigits(6, hour)
  511. buf.tmp[8] = ':'
  512. buf.twoDigits(9, minute)
  513. buf.tmp[11] = ':'
  514. buf.twoDigits(12, second)
  515. buf.tmp[14] = '.'
  516. buf.nDigits(6, 15, now.Nanosecond()/1000, '0')
  517. buf.tmp[21] = ' '
  518. buf.Write(buf.tmp[:22])
  519. buf.WriteString(file)
  520. buf.tmp[0] = ':'
  521. n := buf.someDigits(1, line)
  522. buf.tmp[n+1] = ' '
  523. buf.Write(buf.tmp[:n+2])
  524. return buf
  525. }
  526. // Some custom tiny helper functions to print the log header efficiently.
  527. const digits = "0123456789"
  528. // twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i].
  529. func (buf *buffer) twoDigits(i, d int) {
  530. buf.tmp[i+1] = digits[d%10]
  531. d /= 10
  532. buf.tmp[i] = digits[d%10]
  533. }
  534. // nDigits formats an n-digit integer at buf.tmp[i],
  535. // padding with pad on the left.
  536. // It assumes d >= 0.
  537. func (buf *buffer) nDigits(n, i, d int, pad byte) {
  538. j := n - 1
  539. for ; j >= 0 && d > 0; j-- {
  540. buf.tmp[i+j] = digits[d%10]
  541. d /= 10
  542. }
  543. for ; j >= 0; j-- {
  544. buf.tmp[i+j] = pad
  545. }
  546. }
  547. // someDigits formats a zero-prefixed variable-width integer at buf.tmp[i].
  548. func (buf *buffer) someDigits(i, d int) int {
  549. // Print into the top, then copy down. We know there's space for at least
  550. // a 10-digit number.
  551. j := len(buf.tmp)
  552. for {
  553. j--
  554. buf.tmp[j] = digits[d%10]
  555. d /= 10
  556. if d == 0 {
  557. break
  558. }
  559. }
  560. return copy(buf.tmp[i:], buf.tmp[j:])
  561. }
  562. func (l *loggingT) println(s severity, args ...interface{}) {
  563. buf, file, line := l.header(s, 0)
  564. fmt.Fprintln(buf, args...)
  565. l.output(s, buf, file, line, false)
  566. }
  567. func (l *loggingT) print(s severity, args ...interface{}) {
  568. l.printDepth(s, 1, args...)
  569. }
  570. func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) {
  571. buf, file, line := l.header(s, depth)
  572. fmt.Fprint(buf, args...)
  573. if buf.Bytes()[buf.Len()-1] != '\n' {
  574. buf.WriteByte('\n')
  575. }
  576. l.output(s, buf, file, line, false)
  577. }
  578. func (l *loggingT) printf(s severity, format string, args ...interface{}) {
  579. buf, file, line := l.header(s, 0)
  580. fmt.Fprintf(buf, format, args...)
  581. if buf.Bytes()[buf.Len()-1] != '\n' {
  582. buf.WriteByte('\n')
  583. }
  584. l.output(s, buf, file, line, false)
  585. }
  586. // printWithFileLine behaves like print but uses the provided file and line number. If
  587. // alsoLogToStderr is true, the log message always appears on standard error; it
  588. // will also appear in the log file unless --logtostderr is set.
  589. func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) {
  590. buf := l.formatHeader(s, file, line)
  591. fmt.Fprint(buf, args...)
  592. if buf.Bytes()[buf.Len()-1] != '\n' {
  593. buf.WriteByte('\n')
  594. }
  595. l.output(s, buf, file, line, alsoToStderr)
  596. }
  597. // output writes the data to the log files and releases the buffer.
  598. func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
  599. l.mu.Lock()
  600. if l.traceLocation.isSet() {
  601. if l.traceLocation.match(file, line) {
  602. buf.Write(stacks(false))
  603. }
  604. }
  605. data := buf.Bytes()
  606. if l.toStderr {
  607. os.Stderr.Write(data)
  608. } else {
  609. if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
  610. os.Stderr.Write(data)
  611. }
  612. if l.file[s] == nil {
  613. if err := l.createFiles(s); err != nil {
  614. os.Stderr.Write(data) // Make sure the message appears somewhere.
  615. l.exit(err)
  616. }
  617. }
  618. switch s {
  619. case fatalLog:
  620. l.file[fatalLog].Write(data)
  621. fallthrough
  622. case errorLog:
  623. l.file[errorLog].Write(data)
  624. fallthrough
  625. case warningLog:
  626. l.file[warningLog].Write(data)
  627. fallthrough
  628. case infoLog:
  629. l.file[infoLog].Write(data)
  630. }
  631. }
  632. if s == fatalLog {
  633. // If we got here via Exit rather than Fatal, print no stacks.
  634. if atomic.LoadUint32(&fatalNoStacks) > 0 {
  635. l.mu.Unlock()
  636. timeoutFlush(10 * time.Second)
  637. os.Exit(1)
  638. }
  639. // Dump all goroutine stacks before exiting.
  640. // First, make sure we see the trace for the current goroutine on standard error.
  641. // If -logtostderr has been specified, the loop below will do that anyway
  642. // as the first stack in the full dump.
  643. if !l.toStderr {
  644. os.Stderr.Write(stacks(false))
  645. }
  646. // Write the stack trace for all goroutines to the files.
  647. trace := stacks(true)
  648. logExitFunc = func(error) {} // If we get a write error, we'll still exit below.
  649. for log := fatalLog; log >= infoLog; log-- {
  650. if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.
  651. f.Write(trace)
  652. }
  653. }
  654. l.mu.Unlock()
  655. timeoutFlush(10 * time.Second)
  656. os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.
  657. }
  658. l.putBuffer(buf)
  659. l.mu.Unlock()
  660. if stats := severityStats[s]; stats != nil {
  661. atomic.AddInt64(&stats.lines, 1)
  662. atomic.AddInt64(&stats.bytes, int64(len(data)))
  663. }
  664. }
  665. // timeoutFlush calls Flush and returns when it completes or after timeout
  666. // elapses, whichever happens first. This is needed because the hooks invoked
  667. // by Flush may deadlock when glog.Fatal is called from a hook that holds
  668. // a lock.
  669. func timeoutFlush(timeout time.Duration) {
  670. done := make(chan bool, 1)
  671. go func() {
  672. Flush() // calls logging.lockAndFlushAll()
  673. done <- true
  674. }()
  675. select {
  676. case <-done:
  677. case <-time.After(timeout):
  678. fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout)
  679. }
  680. }
  681. // stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines.
  682. func stacks(all bool) []byte {
  683. // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though.
  684. n := 10000
  685. if all {
  686. n = 100000
  687. }
  688. var trace []byte
  689. for i := 0; i < 5; i++ {
  690. trace = make([]byte, n)
  691. nbytes := runtime.Stack(trace, all)
  692. if nbytes < len(trace) {
  693. return trace[:nbytes]
  694. }
  695. n *= 2
  696. }
  697. return trace
  698. }
  699. // logExitFunc provides a simple mechanism to override the default behavior
  700. // of exiting on error. Used in testing and to guarantee we reach a required exit
  701. // for fatal logs. Instead, exit could be a function rather than a method but that
  702. // would make its use clumsier.
  703. var logExitFunc func(error)
  704. // exit is called if there is trouble creating or writing log files.
  705. // It flushes the logs and exits the program; there's no point in hanging around.
  706. // l.mu is held.
  707. func (l *loggingT) exit(err error) {
  708. fmt.Fprintf(os.Stderr, "glog: exiting because of error: %s\n", err)
  709. // If logExitFunc is set, we do that instead of exiting.
  710. if logExitFunc != nil {
  711. logExitFunc(err)
  712. return
  713. }
  714. l.flushAll()
  715. l.exited = true // os.Exit(2)
  716. }
  717. // syncBuffer joins a bufio.Writer to its underlying file, providing access to the
  718. // file's Sync method and providing a wrapper for the Write method that provides log
  719. // file rotation. There are conflicting methods, so the file cannot be embedded.
  720. // l.mu is held for all its methods.
  721. type syncBuffer struct {
  722. logger *loggingT
  723. *bufio.Writer
  724. file *os.File
  725. sev severity
  726. nbytes uint64 // The number of bytes written to this file
  727. }
  728. func (sb *syncBuffer) Sync() error {
  729. return sb.file.Sync()
  730. }
  731. func (sb *syncBuffer) Write(p []byte) (n int, err error) {
  732. if sb.logger.exited {
  733. return
  734. }
  735. if sb.nbytes+uint64(len(p)) >= MaxSize {
  736. if err := sb.rotateFile(time.Now()); err != nil {
  737. sb.logger.exit(err)
  738. }
  739. }
  740. n, err = sb.Writer.Write(p)
  741. sb.nbytes += uint64(n)
  742. if err != nil {
  743. sb.logger.exit(err)
  744. }
  745. return
  746. }
  747. // rotateFile closes the syncBuffer's file and starts a new one.
  748. func (sb *syncBuffer) rotateFile(now time.Time) error {
  749. if sb.file != nil {
  750. sb.Flush()
  751. sb.file.Close()
  752. }
  753. var err error
  754. sb.file, _, err = create(severityName[sb.sev], now)
  755. sb.nbytes = 0
  756. if err != nil {
  757. return err
  758. }
  759. sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
  760. // Write header.
  761. var buf bytes.Buffer
  762. fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
  763. fmt.Fprintf(&buf, "Running on machine: %s\n", host)
  764. fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
  765. fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss threadid file:line] msg\n")
  766. n, err := sb.file.Write(buf.Bytes())
  767. sb.nbytes += uint64(n)
  768. return err
  769. }
  770. // bufferSize sizes the buffer associated with each log file. It's large
  771. // so that log records can accumulate without the logging thread blocking
  772. // on disk I/O. The flushDaemon will block instead.
  773. const bufferSize = 256 * 1024
  774. // createFiles creates all the log files for severity from sev down to infoLog.
  775. // l.mu is held.
  776. func (l *loggingT) createFiles(sev severity) error {
  777. now := time.Now()
  778. // Files are created in decreasing severity order, so as soon as we find one
  779. // has already been created, we can stop.
  780. for s := sev; s >= infoLog && l.file[s] == nil; s-- {
  781. sb := &syncBuffer{
  782. logger: l,
  783. sev: s,
  784. }
  785. if err := sb.rotateFile(now); err != nil {
  786. return err
  787. }
  788. l.file[s] = sb
  789. }
  790. return nil
  791. }
  792. const flushInterval = 30 * time.Second
  793. // flushDaemon periodically flushes the log file buffers.
  794. func (l *loggingT) flushDaemon() {
  795. for _ = range time.NewTicker(flushInterval).C {
  796. l.lockAndFlushAll()
  797. }
  798. }
  799. // lockAndFlushAll is like flushAll but locks l.mu first.
  800. func (l *loggingT) lockAndFlushAll() {
  801. l.mu.Lock()
  802. l.flushAll()
  803. l.mu.Unlock()
  804. }
  805. // flushAll flushes all the logs and attempts to "sync" their data to disk.
  806. // l.mu is held.
  807. func (l *loggingT) flushAll() {
  808. // Flush from fatal down, in case there's trouble flushing.
  809. for s := fatalLog; s >= infoLog; s-- {
  810. file := l.file[s]
  811. if file != nil {
  812. file.Flush() // ignore error
  813. file.Sync() // ignore error
  814. }
  815. }
  816. }
  817. // CopyStandardLogTo arranges for messages written to the Go "log" package's
  818. // default logs to also appear in the Google logs for the named and lower
  819. // severities. Subsequent changes to the standard log's default output location
  820. // or format may break this behavior.
  821. //
  822. // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
  823. // recognized, CopyStandardLogTo panics.
  824. func CopyStandardLogTo(name string) {
  825. sev, ok := severityByName(name)
  826. if !ok {
  827. panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
  828. }
  829. // Set a log format that captures the user's file and line:
  830. // d.go:23: message
  831. stdLog.SetFlags(stdLog.Lshortfile)
  832. stdLog.SetOutput(logBridge(sev))
  833. }
  834. // logBridge provides the Write method that enables CopyStandardLogTo to connect
  835. // Go's standard logs to the logs provided by this package.
  836. type logBridge severity
  837. // Write parses the standard logging line and passes its components to the
  838. // logger for severity(lb).
  839. func (lb logBridge) Write(b []byte) (n int, err error) {
  840. var (
  841. file = "???"
  842. line = 1
  843. text string
  844. )
  845. // Split "d.go:23: message" into "d.go", "23", and "message".
  846. if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
  847. text = fmt.Sprintf("bad log format: %s", b)
  848. } else {
  849. file = string(parts[0])
  850. text = string(parts[2][1:]) // skip leading space
  851. line, err = strconv.Atoi(string(parts[1]))
  852. if err != nil {
  853. text = fmt.Sprintf("bad line number: %s", b)
  854. line = 1
  855. }
  856. }
  857. // printWithFileLine with alsoToStderr=true, so standard log messages
  858. // always appear on standard error.
  859. logging.printWithFileLine(severity(lb), file, line, true, text)
  860. return len(b), nil
  861. }
  862. // setV computes and remembers the V level for a given PC
  863. // when vmodule is enabled.
  864. // File pattern matching takes the basename of the file, stripped
  865. // of its .go suffix, and uses filepath.Match, which is a little more
  866. // general than the *? matching used in C++.
  867. // l.mu is held.
  868. func (l *loggingT) setV(pc uintptr) Level {
  869. fn := runtime.FuncForPC(pc)
  870. file, _ := fn.FileLine(pc)
  871. // The file is something like /a/b/c/d.go. We want just the d.
  872. if strings.HasSuffix(file, ".go") {
  873. file = file[:len(file)-3]
  874. }
  875. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  876. file = file[slash+1:]
  877. }
  878. for _, filter := range l.vmodule.filter {
  879. if filter.match(file) {
  880. l.vmap[pc] = filter.level
  881. return filter.level
  882. }
  883. }
  884. l.vmap[pc] = 0
  885. return 0
  886. }
  887. // Verbose is a boolean type that implements Infof (like Printf) etc.
  888. // See the documentation of V for more information.
  889. type Verbose bool
  890. // V reports whether verbosity at the call site is at least the requested level.
  891. // The returned value is a boolean of type Verbose, which implements Info, Infoln
  892. // and Infof. These methods will write to the Info log if called.
  893. // Thus, one may write either
  894. // if glog.V(2) { glog.Info("log this") }
  895. // or
  896. // glog.V(2).Info("log this")
  897. // The second form is shorter but the first is cheaper if logging is off because it does
  898. // not evaluate its arguments.
  899. //
  900. // Whether an individual call to V generates a log record depends on the setting of
  901. // the -v and --vmodule flags; both are off by default. If the level in the call to
  902. // V is at least the value of -v, or of -vmodule for the source file containing the
  903. // call, the V call will log.
  904. func V(level Level) Verbose {
  905. // This function tries hard to be cheap unless there's work to do.
  906. // The fast path is two atomic loads and compares.
  907. // Here is a cheap but safe test to see if V logging is enabled globally.
  908. if logging.verbosity.get() >= level {
  909. return Verbose(true)
  910. }
  911. // It's off globally but it vmodule may still be set.
  912. // Here is another cheap but safe test to see if vmodule is enabled.
  913. if atomic.LoadInt32(&logging.filterLength) > 0 {
  914. // Now we need a proper lock to use the logging structure. The pcs field
  915. // is shared so we must lock before accessing it. This is fairly expensive,
  916. // but if V logging is enabled we're slow anyway.
  917. logging.mu.Lock()
  918. defer logging.mu.Unlock()
  919. if runtime.Callers(2, logging.pcs[:]) == 0 {
  920. return Verbose(false)
  921. }
  922. v, ok := logging.vmap[logging.pcs[0]]
  923. if !ok {
  924. v = logging.setV(logging.pcs[0])
  925. }
  926. return Verbose(v >= level)
  927. }
  928. return Verbose(false)
  929. }
  930. // Info is equivalent to the global Info function, guarded by the value of v.
  931. // See the documentation of V for usage.
  932. func (v Verbose) Info(args ...interface{}) {
  933. if v {
  934. logging.print(infoLog, args...)
  935. }
  936. }
  937. // Infoln is equivalent to the global Infoln function, guarded by the value of v.
  938. // See the documentation of V for usage.
  939. func (v Verbose) Infoln(args ...interface{}) {
  940. if v {
  941. logging.println(infoLog, args...)
  942. }
  943. }
  944. // Infof is equivalent to the global Infof function, guarded by the value of v.
  945. // See the documentation of V for usage.
  946. func (v Verbose) Infof(format string, args ...interface{}) {
  947. if v {
  948. logging.printf(infoLog, format, args...)
  949. }
  950. }
  951. // Info logs to the INFO log.
  952. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  953. func Info(args ...interface{}) {
  954. logging.print(infoLog, args...)
  955. }
  956. // InfoDepth acts as Info but uses depth to determine which call frame to log.
  957. // InfoDepth(0, "msg") is the same as Info("msg").
  958. func InfoDepth(depth int, args ...interface{}) {
  959. logging.printDepth(infoLog, depth, args...)
  960. }
  961. // Infoln logs to the INFO log.
  962. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  963. func Infoln(args ...interface{}) {
  964. logging.println(infoLog, args...)
  965. }
  966. // Infof logs to the INFO log.
  967. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  968. func Infof(format string, args ...interface{}) {
  969. logging.printf(infoLog, format, args...)
  970. }
  971. // Warning logs to the WARNING and INFO logs.
  972. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  973. func Warning(args ...interface{}) {
  974. logging.print(warningLog, args...)
  975. }
  976. // WarningDepth acts as Warning but uses depth to determine which call frame to log.
  977. // WarningDepth(0, "msg") is the same as Warning("msg").
  978. func WarningDepth(depth int, args ...interface{}) {
  979. logging.printDepth(warningLog, depth, args...)
  980. }
  981. // Warningln logs to the WARNING and INFO logs.
  982. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  983. func Warningln(args ...interface{}) {
  984. logging.println(warningLog, args...)
  985. }
  986. // Warningf logs to the WARNING and INFO logs.
  987. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  988. func Warningf(format string, args ...interface{}) {
  989. logging.printf(warningLog, format, args...)
  990. }
  991. // Error logs to the ERROR, WARNING, and INFO logs.
  992. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  993. func Error(args ...interface{}) {
  994. logging.print(errorLog, args...)
  995. }
  996. // ErrorDepth acts as Error but uses depth to determine which call frame to log.
  997. // ErrorDepth(0, "msg") is the same as Error("msg").
  998. func ErrorDepth(depth int, args ...interface{}) {
  999. logging.printDepth(errorLog, depth, args...)
  1000. }
  1001. // Errorln logs to the ERROR, WARNING, and INFO logs.
  1002. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  1003. func Errorln(args ...interface{}) {
  1004. logging.println(errorLog, args...)
  1005. }
  1006. // Errorf logs to the ERROR, WARNING, and INFO logs.
  1007. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1008. func Errorf(format string, args ...interface{}) {
  1009. logging.printf(errorLog, format, args...)
  1010. }
  1011. // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
  1012. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1013. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1014. func Fatal(args ...interface{}) {
  1015. logging.print(fatalLog, args...)
  1016. }
  1017. // FatalDepth acts as Fatal but uses depth to determine which call frame to log.
  1018. // FatalDepth(0, "msg") is the same as Fatal("msg").
  1019. func FatalDepth(depth int, args ...interface{}) {
  1020. logging.printDepth(fatalLog, depth, args...)
  1021. }
  1022. // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
  1023. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1024. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  1025. func Fatalln(args ...interface{}) {
  1026. logging.println(fatalLog, args...)
  1027. }
  1028. // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs,
  1029. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1030. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1031. func Fatalf(format string, args ...interface{}) {
  1032. logging.printf(fatalLog, format, args...)
  1033. }
  1034. // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks.
  1035. // It allows Exit and relatives to use the Fatal logs.
  1036. var fatalNoStacks uint32
  1037. // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1038. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1039. func Exit(args ...interface{}) {
  1040. atomic.StoreUint32(&fatalNoStacks, 1)
  1041. logging.print(fatalLog, args...)
  1042. }
  1043. // ExitDepth acts as Exit but uses depth to determine which call frame to log.
  1044. // ExitDepth(0, "msg") is the same as Exit("msg").
  1045. func ExitDepth(depth int, args ...interface{}) {
  1046. atomic.StoreUint32(&fatalNoStacks, 1)
  1047. logging.printDepth(fatalLog, depth, args...)
  1048. }
  1049. // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1050. func Exitln(args ...interface{}) {
  1051. atomic.StoreUint32(&fatalNoStacks, 1)
  1052. logging.println(fatalLog, args...)
  1053. }
  1054. // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1055. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1056. func Exitf(format string, args ...interface{}) {
  1057. atomic.StoreUint32(&fatalNoStacks, 1)
  1058. logging.printf(fatalLog, format, args...)
  1059. }