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.

1186 lines
36 KiB

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