glog.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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/chrislusf/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(5, 15, pid, ' ') // TODO: should be TID
  517. buf.tmp[20] = ' '
  518. buf.Write(buf.tmp[:21])
  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, "glog: 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. l.exited = true // 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.logger.exited {
  734. return
  735. }
  736. if sb.nbytes+uint64(len(p)) >= MaxSize {
  737. if err := sb.rotateFile(time.Now()); err != nil {
  738. sb.logger.exit(err)
  739. }
  740. }
  741. n, err = sb.Writer.Write(p)
  742. sb.nbytes += uint64(n)
  743. if err != nil {
  744. sb.logger.exit(err)
  745. }
  746. return
  747. }
  748. // rotateFile closes the syncBuffer's file and starts a new one.
  749. func (sb *syncBuffer) rotateFile(now time.Time) error {
  750. if sb.file != nil {
  751. sb.Flush()
  752. sb.file.Close()
  753. }
  754. var err error
  755. sb.file, _, err = create(severityName[sb.sev], now)
  756. sb.nbytes = 0
  757. if err != nil {
  758. return err
  759. }
  760. sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
  761. // Write header.
  762. var buf bytes.Buffer
  763. fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
  764. fmt.Fprintf(&buf, "Running on machine: %s\n", host)
  765. fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
  766. fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss threadid file:line] msg\n")
  767. n, err := sb.file.Write(buf.Bytes())
  768. sb.nbytes += uint64(n)
  769. return err
  770. }
  771. // bufferSize sizes the buffer associated with each log file. It's large
  772. // so that log records can accumulate without the logging thread blocking
  773. // on disk I/O. The flushDaemon will block instead.
  774. const bufferSize = 256 * 1024
  775. // createFiles creates all the log files for severity from sev down to infoLog.
  776. // l.mu is held.
  777. func (l *loggingT) createFiles(sev severity) error {
  778. now := time.Now()
  779. // Files are created in decreasing severity order, so as soon as we find one
  780. // has already been created, we can stop.
  781. for s := sev; s >= infoLog && l.file[s] == nil; s-- {
  782. sb := &syncBuffer{
  783. logger: l,
  784. sev: s,
  785. }
  786. if err := sb.rotateFile(now); err != nil {
  787. return err
  788. }
  789. l.file[s] = sb
  790. }
  791. return nil
  792. }
  793. const flushInterval = 30 * time.Second
  794. // flushDaemon periodically flushes the log file buffers.
  795. func (l *loggingT) flushDaemon() {
  796. for _ = range time.NewTicker(flushInterval).C {
  797. l.lockAndFlushAll()
  798. }
  799. }
  800. // lockAndFlushAll is like flushAll but locks l.mu first.
  801. func (l *loggingT) lockAndFlushAll() {
  802. l.mu.Lock()
  803. l.flushAll()
  804. l.mu.Unlock()
  805. }
  806. // flushAll flushes all the logs and attempts to "sync" their data to disk.
  807. // l.mu is held.
  808. func (l *loggingT) flushAll() {
  809. // Flush from fatal down, in case there's trouble flushing.
  810. for s := fatalLog; s >= infoLog; s-- {
  811. file := l.file[s]
  812. if file != nil {
  813. file.Flush() // ignore error
  814. file.Sync() // ignore error
  815. }
  816. }
  817. }
  818. // CopyStandardLogTo arranges for messages written to the Go "log" package's
  819. // default logs to also appear in the Google logs for the named and lower
  820. // severities. Subsequent changes to the standard log's default output location
  821. // or format may break this behavior.
  822. //
  823. // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
  824. // recognized, CopyStandardLogTo panics.
  825. func CopyStandardLogTo(name string) {
  826. sev, ok := severityByName(name)
  827. if !ok {
  828. panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
  829. }
  830. // Set a log format that captures the user's file and line:
  831. // d.go:23: message
  832. stdLog.SetFlags(stdLog.Lshortfile)
  833. stdLog.SetOutput(logBridge(sev))
  834. }
  835. // logBridge provides the Write method that enables CopyStandardLogTo to connect
  836. // Go's standard logs to the logs provided by this package.
  837. type logBridge severity
  838. // Write parses the standard logging line and passes its components to the
  839. // logger for severity(lb).
  840. func (lb logBridge) Write(b []byte) (n int, err error) {
  841. var (
  842. file = "???"
  843. line = 1
  844. text string
  845. )
  846. // Split "d.go:23: message" into "d.go", "23", and "message".
  847. if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
  848. text = fmt.Sprintf("bad log format: %s", b)
  849. } else {
  850. file = string(parts[0])
  851. text = string(parts[2][1:]) // skip leading space
  852. line, err = strconv.Atoi(string(parts[1]))
  853. if err != nil {
  854. text = fmt.Sprintf("bad line number: %s", b)
  855. line = 1
  856. }
  857. }
  858. // printWithFileLine with alsoToStderr=true, so standard log messages
  859. // always appear on standard error.
  860. logging.printWithFileLine(severity(lb), file, line, true, text)
  861. return len(b), nil
  862. }
  863. // setV computes and remembers the V level for a given PC
  864. // when vmodule is enabled.
  865. // File pattern matching takes the basename of the file, stripped
  866. // of its .go suffix, and uses filepath.Match, which is a little more
  867. // general than the *? matching used in C++.
  868. // l.mu is held.
  869. func (l *loggingT) setV(pc uintptr) Level {
  870. fn := runtime.FuncForPC(pc)
  871. file, _ := fn.FileLine(pc)
  872. // The file is something like /a/b/c/d.go. We want just the d.
  873. if strings.HasSuffix(file, ".go") {
  874. file = file[:len(file)-3]
  875. }
  876. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  877. file = file[slash+1:]
  878. }
  879. for _, filter := range l.vmodule.filter {
  880. if filter.match(file) {
  881. l.vmap[pc] = filter.level
  882. return filter.level
  883. }
  884. }
  885. l.vmap[pc] = 0
  886. return 0
  887. }
  888. // Verbose is a boolean type that implements Infof (like Printf) etc.
  889. // See the documentation of V for more information.
  890. type Verbose bool
  891. // V reports whether verbosity at the call site is at least the requested level.
  892. // The returned value is a boolean of type Verbose, which implements Info, Infoln
  893. // and Infof. These methods will write to the Info log if called.
  894. // Thus, one may write either
  895. // if glog.V(2) { glog.Info("log this") }
  896. // or
  897. // glog.V(2).Info("log this")
  898. // The second form is shorter but the first is cheaper if logging is off because it does
  899. // not evaluate its arguments.
  900. //
  901. // Whether an individual call to V generates a log record depends on the setting of
  902. // the -v and --vmodule flags; both are off by default. If the level in the call to
  903. // V is at least the value of -v, or of -vmodule for the source file containing the
  904. // call, the V call will log.
  905. func V(level Level) Verbose {
  906. // This function tries hard to be cheap unless there's work to do.
  907. // The fast path is two atomic loads and compares.
  908. // Here is a cheap but safe test to see if V logging is enabled globally.
  909. if logging.verbosity.get() >= level {
  910. return Verbose(true)
  911. }
  912. // It's off globally but it vmodule may still be set.
  913. // Here is another cheap but safe test to see if vmodule is enabled.
  914. if atomic.LoadInt32(&logging.filterLength) > 0 {
  915. // Now we need a proper lock to use the logging structure. The pcs field
  916. // is shared so we must lock before accessing it. This is fairly expensive,
  917. // but if V logging is enabled we're slow anyway.
  918. logging.mu.Lock()
  919. defer logging.mu.Unlock()
  920. if runtime.Callers(2, logging.pcs[:]) == 0 {
  921. return Verbose(false)
  922. }
  923. v, ok := logging.vmap[logging.pcs[0]]
  924. if !ok {
  925. v = logging.setV(logging.pcs[0])
  926. }
  927. return Verbose(v >= level)
  928. }
  929. return Verbose(false)
  930. }
  931. // Info is equivalent to the global Info function, guarded by the value of v.
  932. // See the documentation of V for usage.
  933. func (v Verbose) Info(args ...interface{}) {
  934. if v {
  935. logging.print(infoLog, args...)
  936. }
  937. }
  938. // Infoln is equivalent to the global Infoln function, guarded by the value of v.
  939. // See the documentation of V for usage.
  940. func (v Verbose) Infoln(args ...interface{}) {
  941. if v {
  942. logging.println(infoLog, args...)
  943. }
  944. }
  945. // Infof is equivalent to the global Infof function, guarded by the value of v.
  946. // See the documentation of V for usage.
  947. func (v Verbose) Infof(format string, args ...interface{}) {
  948. if v {
  949. logging.printf(infoLog, format, args...)
  950. }
  951. }
  952. // Info logs to the INFO log.
  953. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  954. func Info(args ...interface{}) {
  955. logging.print(infoLog, args...)
  956. }
  957. // InfoDepth acts as Info but uses depth to determine which call frame to log.
  958. // InfoDepth(0, "msg") is the same as Info("msg").
  959. func InfoDepth(depth int, args ...interface{}) {
  960. logging.printDepth(infoLog, depth, args...)
  961. }
  962. // Infoln logs to the INFO log.
  963. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  964. func Infoln(args ...interface{}) {
  965. logging.println(infoLog, args...)
  966. }
  967. // Infof logs to the INFO log.
  968. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  969. func Infof(format string, args ...interface{}) {
  970. logging.printf(infoLog, format, args...)
  971. }
  972. // Warning logs to the WARNING and INFO logs.
  973. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  974. func Warning(args ...interface{}) {
  975. logging.print(warningLog, args...)
  976. }
  977. // WarningDepth acts as Warning but uses depth to determine which call frame to log.
  978. // WarningDepth(0, "msg") is the same as Warning("msg").
  979. func WarningDepth(depth int, args ...interface{}) {
  980. logging.printDepth(warningLog, depth, args...)
  981. }
  982. // Warningln logs to the WARNING and INFO logs.
  983. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  984. func Warningln(args ...interface{}) {
  985. logging.println(warningLog, args...)
  986. }
  987. // Warningf logs to the WARNING and INFO logs.
  988. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  989. func Warningf(format string, args ...interface{}) {
  990. logging.printf(warningLog, format, args...)
  991. }
  992. // Error logs to the ERROR, WARNING, and INFO logs.
  993. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  994. func Error(args ...interface{}) {
  995. logging.print(errorLog, args...)
  996. }
  997. // ErrorDepth acts as Error but uses depth to determine which call frame to log.
  998. // ErrorDepth(0, "msg") is the same as Error("msg").
  999. func ErrorDepth(depth int, args ...interface{}) {
  1000. logging.printDepth(errorLog, depth, args...)
  1001. }
  1002. // Errorln logs to the ERROR, WARNING, and INFO logs.
  1003. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  1004. func Errorln(args ...interface{}) {
  1005. logging.println(errorLog, args...)
  1006. }
  1007. // Errorf logs to the ERROR, WARNING, and INFO logs.
  1008. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1009. func Errorf(format string, args ...interface{}) {
  1010. logging.printf(errorLog, format, args...)
  1011. }
  1012. // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
  1013. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1014. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1015. func Fatal(args ...interface{}) {
  1016. logging.print(fatalLog, args...)
  1017. }
  1018. // FatalDepth acts as Fatal but uses depth to determine which call frame to log.
  1019. // FatalDepth(0, "msg") is the same as Fatal("msg").
  1020. func FatalDepth(depth int, args ...interface{}) {
  1021. logging.printDepth(fatalLog, depth, args...)
  1022. }
  1023. // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
  1024. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1025. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
  1026. func Fatalln(args ...interface{}) {
  1027. logging.println(fatalLog, args...)
  1028. }
  1029. // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs,
  1030. // including a stack trace of all running goroutines, then calls os.Exit(255).
  1031. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1032. func Fatalf(format string, args ...interface{}) {
  1033. logging.printf(fatalLog, format, args...)
  1034. }
  1035. // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks.
  1036. // It allows Exit and relatives to use the Fatal logs.
  1037. var fatalNoStacks uint32
  1038. // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1039. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
  1040. func Exit(args ...interface{}) {
  1041. atomic.StoreUint32(&fatalNoStacks, 1)
  1042. logging.print(fatalLog, args...)
  1043. }
  1044. // ExitDepth acts as Exit but uses depth to determine which call frame to log.
  1045. // ExitDepth(0, "msg") is the same as Exit("msg").
  1046. func ExitDepth(depth int, args ...interface{}) {
  1047. atomic.StoreUint32(&fatalNoStacks, 1)
  1048. logging.printDepth(fatalLog, depth, args...)
  1049. }
  1050. // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1051. func Exitln(args ...interface{}) {
  1052. atomic.StoreUint32(&fatalNoStacks, 1)
  1053. logging.println(fatalLog, args...)
  1054. }
  1055. // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
  1056. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
  1057. func Exitf(format string, args ...interface{}) {
  1058. atomic.StoreUint32(&fatalNoStacks, 1)
  1059. logging.printf(fatalLog, format, args...)
  1060. }