glog.go 36 KB

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