logext.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. package log
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "os"
  7. "runtime"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. // These flags define which text to prefix to each log entry generated by the Logger.
  13. const (
  14. // Bits or'ed together to control what's printed. There is no control over the
  15. // order they appear (the order listed here) or the format they present (as
  16. // described in the comments). A colon appears after these items:
  17. // 2009/0123 01:23:23.123123 /a/b/c/d.go:23: message
  18. Ldate = 1 << iota // the date: 2009/0123
  19. Ltime // the time: 01:23:23
  20. Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
  21. Llongfile // full file name and line number: /a/b/c/d.go:23
  22. Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
  23. Lmodule // module name
  24. Llevel // level: 0(Debug), 1(Info), 2(Warn), 3(Error), 4(Panic), 5(Fatal)
  25. Llongcolor // color will start [info] end of line
  26. Lshortcolor // color only include [info]
  27. LstdFlags = Ldate | Ltime // initial values for the standard logger
  28. //Ldefault = Llevel | LstdFlags | Lshortfile | Llongcolor
  29. ) // [prefix][time][level][module][shortfile|longfile]
  30. func Ldefault() int {
  31. if runtime.GOOS == "windows" {
  32. return Llevel | LstdFlags | Lshortfile
  33. }
  34. return Llevel | LstdFlags | Lshortfile | Llongcolor
  35. }
  36. const (
  37. Lall = iota
  38. )
  39. const (
  40. Ldebug = iota
  41. Linfo
  42. Lwarn
  43. Lerror
  44. Lpanic
  45. Lfatal
  46. Lnone
  47. )
  48. const (
  49. ForeBlack = iota + 30 //30
  50. ForeRed //31
  51. ForeGreen //32
  52. ForeYellow //33
  53. ForeBlue //34
  54. ForePurple //35
  55. ForeCyan //36
  56. ForeWhite //37
  57. )
  58. const (
  59. BackBlack = iota + 40 //40
  60. BackRed //41
  61. BackGreen //42
  62. BackYellow //43
  63. BackBlue //44
  64. BackPurple //45
  65. BackCyan //46
  66. BackWhite //47
  67. )
  68. var levels = []string{
  69. "[Debug]",
  70. "[Info]",
  71. "[Warn]",
  72. "[Error]",
  73. "[Panic]",
  74. "[Fatal]",
  75. }
  76. // MUST called before all logs
  77. func SetLevels(lvs []string) {
  78. levels = lvs
  79. }
  80. var colors = []int{
  81. ForeCyan,
  82. ForeGreen,
  83. ForeYellow,
  84. ForeRed,
  85. ForePurple,
  86. ForeBlue,
  87. }
  88. // MUST called before all logs
  89. func SetColors(cls []int) {
  90. colors = cls
  91. }
  92. // A Logger represents an active logging object that generates lines of
  93. // output to an io.Writer. Each logging operation makes a single call to
  94. // the Writer's Write method. A Logger can be used simultaneously from
  95. // multiple goroutines; it guarantees to serialize access to the Writer.
  96. type Logger struct {
  97. mu sync.Mutex // ensures atomic writes; protects the following fields
  98. prefix string // prefix to write at beginning of each line
  99. flag int // properties
  100. Level int
  101. out io.Writer // destination for output
  102. buf bytes.Buffer // for accumulating text to write
  103. levelStats [6]int64
  104. }
  105. // New creates a new Logger. The out variable sets the
  106. // destination to which log data will be written.
  107. // The prefix appears at the beginning of each generated log line.
  108. // The flag argument defines the logging properties.
  109. func New(out io.Writer, prefix string, flag int) *Logger {
  110. return &Logger{out: out, prefix: prefix, Level: 1, flag: flag}
  111. }
  112. var Std = New(os.Stderr, "", Ldefault())
  113. // Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
  114. // Knows the buffer has capacity.
  115. func itoa(buf *bytes.Buffer, i int, wid int) {
  116. var u uint = uint(i)
  117. if u == 0 && wid <= 1 {
  118. buf.WriteByte('0')
  119. return
  120. }
  121. // Assemble decimal in reverse order.
  122. var b [32]byte
  123. bp := len(b)
  124. for ; u > 0 || wid > 0; u /= 10 {
  125. bp--
  126. wid--
  127. b[bp] = byte(u%10) + '0'
  128. }
  129. // avoid slicing b to avoid an allocation.
  130. for bp < len(b) {
  131. buf.WriteByte(b[bp])
  132. bp++
  133. }
  134. }
  135. func moduleOf(file string) string {
  136. pos := strings.LastIndex(file, "/")
  137. if pos != -1 {
  138. pos1 := strings.LastIndex(file[:pos], "/src/")
  139. if pos1 != -1 {
  140. return file[pos1+5 : pos]
  141. }
  142. }
  143. return "UNKNOWN"
  144. }
  145. func (l *Logger) formatHeader(buf *bytes.Buffer, t time.Time,
  146. file string, line int, lvl int, reqId string) {
  147. if l.prefix != "" {
  148. buf.WriteString(l.prefix)
  149. }
  150. if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
  151. if l.flag&Ldate != 0 {
  152. year, month, day := t.Date()
  153. itoa(buf, year, 4)
  154. buf.WriteByte('/')
  155. itoa(buf, int(month), 2)
  156. buf.WriteByte('/')
  157. itoa(buf, day, 2)
  158. buf.WriteByte(' ')
  159. }
  160. if l.flag&(Ltime|Lmicroseconds) != 0 {
  161. hour, min, sec := t.Clock()
  162. itoa(buf, hour, 2)
  163. buf.WriteByte(':')
  164. itoa(buf, min, 2)
  165. buf.WriteByte(':')
  166. itoa(buf, sec, 2)
  167. if l.flag&Lmicroseconds != 0 {
  168. buf.WriteByte('.')
  169. itoa(buf, t.Nanosecond()/1e3, 6)
  170. }
  171. buf.WriteByte(' ')
  172. }
  173. }
  174. if reqId != "" {
  175. buf.WriteByte('[')
  176. buf.WriteString(reqId)
  177. buf.WriteByte(']')
  178. buf.WriteByte(' ')
  179. }
  180. if l.flag&(Lshortcolor|Llongcolor) != 0 {
  181. buf.WriteString(fmt.Sprintf("\033[1;%dm", colors[lvl]))
  182. }
  183. if l.flag&Llevel != 0 {
  184. buf.WriteString(levels[lvl])
  185. buf.WriteByte(' ')
  186. }
  187. if l.flag&Lshortcolor != 0 {
  188. buf.WriteString("\033[0m")
  189. }
  190. if l.flag&Lmodule != 0 {
  191. buf.WriteByte('[')
  192. buf.WriteString(moduleOf(file))
  193. buf.WriteByte(']')
  194. buf.WriteByte(' ')
  195. }
  196. if l.flag&(Lshortfile|Llongfile) != 0 {
  197. if l.flag&Lshortfile != 0 {
  198. short := file
  199. for i := len(file) - 1; i > 0; i-- {
  200. if file[i] == '/' {
  201. short = file[i+1:]
  202. break
  203. }
  204. }
  205. file = short
  206. }
  207. buf.WriteString(file)
  208. buf.WriteByte(':')
  209. itoa(buf, line, -1)
  210. buf.WriteByte(' ')
  211. }
  212. }
  213. // Output writes the output for a logging event. The string s contains
  214. // the text to print after the prefix specified by the flags of the
  215. // Logger. A newline is appended if the last character of s is not
  216. // already a newline. Calldepth is used to recover the PC and is
  217. // provided for generality, although at the moment on all pre-defined
  218. // paths it will be 2.
  219. func (l *Logger) Output(reqId string, lvl int, calldepth int, s string) error {
  220. if lvl < l.Level {
  221. return nil
  222. }
  223. now := time.Now() // get this early.
  224. var file string
  225. var line int
  226. l.mu.Lock()
  227. defer l.mu.Unlock()
  228. if l.flag&(Lshortfile|Llongfile|Lmodule) != 0 {
  229. // release lock while getting caller info - it's expensive.
  230. l.mu.Unlock()
  231. var ok bool
  232. _, file, line, ok = runtime.Caller(calldepth)
  233. if !ok {
  234. file = "???"
  235. line = 0
  236. }
  237. l.mu.Lock()
  238. }
  239. l.levelStats[lvl]++
  240. l.buf.Reset()
  241. l.formatHeader(&l.buf, now, file, line, lvl, reqId)
  242. l.buf.WriteString(s)
  243. if l.flag&Llongcolor != 0 {
  244. l.buf.WriteString("\033[0m")
  245. }
  246. if len(s) > 0 && s[len(s)-1] != '\n' {
  247. l.buf.WriteByte('\n')
  248. }
  249. _, err := l.out.Write(l.buf.Bytes())
  250. return err
  251. }
  252. // -----------------------------------------
  253. // Printf calls l.Output to print to the logger.
  254. // Arguments are handled in the manner of fmt.Printf.
  255. func (l *Logger) Printf(format string, v ...interface{}) {
  256. l.Output("", Linfo, 2, fmt.Sprintf(format, v...))
  257. }
  258. // Print calls l.Output to print to the logger.
  259. // Arguments are handled in the manner of fmt.Print.
  260. func (l *Logger) Print(v ...interface{}) {
  261. l.Output("", Linfo, 2, fmt.Sprint(v...))
  262. }
  263. // Println calls l.Output to print to the logger.
  264. // Arguments are handled in the manner of fmt.Println.
  265. func (l *Logger) Println(v ...interface{}) {
  266. l.Output("", Linfo, 2, fmt.Sprintln(v...))
  267. }
  268. // -----------------------------------------
  269. func (l *Logger) Debugf(format string, v ...interface{}) {
  270. if Ldebug < l.Level {
  271. return
  272. }
  273. l.Output("", Ldebug, 2, fmt.Sprintf(format, v...))
  274. }
  275. func (l *Logger) Debug(v ...interface{}) {
  276. if Ldebug < l.Level {
  277. return
  278. }
  279. l.Output("", Ldebug, 2, fmt.Sprintln(v...))
  280. }
  281. // -----------------------------------------
  282. func (l *Logger) Infof(format string, v ...interface{}) {
  283. if Linfo < l.Level {
  284. return
  285. }
  286. l.Output("", Linfo, 2, fmt.Sprintf(format, v...))
  287. }
  288. func (l *Logger) Info(v ...interface{}) {
  289. if Linfo < l.Level {
  290. return
  291. }
  292. l.Output("", Linfo, 2, fmt.Sprintln(v...))
  293. }
  294. // -----------------------------------------
  295. func (l *Logger) Warnf(format string, v ...interface{}) {
  296. if Lwarn < l.Level {
  297. return
  298. }
  299. l.Output("", Lwarn, 2, fmt.Sprintf(format, v...))
  300. }
  301. func (l *Logger) Warn(v ...interface{}) {
  302. if Lwarn < l.Level {
  303. return
  304. }
  305. l.Output("", Lwarn, 2, fmt.Sprintln(v...))
  306. }
  307. // -----------------------------------------
  308. func (l *Logger) Errorf(format string, v ...interface{}) {
  309. if Lerror < l.Level {
  310. return
  311. }
  312. l.Output("", Lerror, 2, fmt.Sprintf(format, v...))
  313. }
  314. func (l *Logger) Error(v ...interface{}) {
  315. if Lerror < l.Level {
  316. return
  317. }
  318. l.Output("", Lerror, 2, fmt.Sprintln(v...))
  319. }
  320. // -----------------------------------------
  321. func (l *Logger) Fatal(v ...interface{}) {
  322. if Lfatal < l.Level {
  323. return
  324. }
  325. l.Output("", Lfatal, 2, fmt.Sprintln(v...))
  326. os.Exit(1)
  327. }
  328. // Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).
  329. func (l *Logger) Fatalf(format string, v ...interface{}) {
  330. if Lfatal < l.Level {
  331. return
  332. }
  333. l.Output("", Lfatal, 2, fmt.Sprintf(format, v...))
  334. os.Exit(1)
  335. }
  336. // -----------------------------------------
  337. // Panic is equivalent to l.Print() followed by a call to panic().
  338. func (l *Logger) Panic(v ...interface{}) {
  339. if Lpanic < l.Level {
  340. return
  341. }
  342. s := fmt.Sprintln(v...)
  343. l.Output("", Lpanic, 2, s)
  344. panic(s)
  345. }
  346. // Panicf is equivalent to l.Printf() followed by a call to panic().
  347. func (l *Logger) Panicf(format string, v ...interface{}) {
  348. if Lpanic < l.Level {
  349. return
  350. }
  351. s := fmt.Sprintf(format, v...)
  352. l.Output("", Lpanic, 2, s)
  353. panic(s)
  354. }
  355. // -----------------------------------------
  356. func (l *Logger) Stack(v ...interface{}) {
  357. s := fmt.Sprint(v...)
  358. s += "\n"
  359. buf := make([]byte, 1024*1024)
  360. n := runtime.Stack(buf, true)
  361. s += string(buf[:n])
  362. s += "\n"
  363. l.Output("", Lerror, 2, s)
  364. }
  365. // -----------------------------------------
  366. func (l *Logger) Stat() (stats []int64) {
  367. l.mu.Lock()
  368. v := l.levelStats
  369. l.mu.Unlock()
  370. return v[:]
  371. }
  372. // Flags returns the output flags for the logger.
  373. func (l *Logger) Flags() int {
  374. l.mu.Lock()
  375. defer l.mu.Unlock()
  376. return l.flag
  377. }
  378. func RmColorFlags(flag int) int {
  379. // for un std out, it should not show color since almost them don't support
  380. if flag&Llongcolor != 0 {
  381. flag = flag ^ Llongcolor
  382. }
  383. if flag&Lshortcolor != 0 {
  384. flag = flag ^ Lshortcolor
  385. }
  386. return flag
  387. }
  388. // SetFlags sets the output flags for the logger.
  389. func (l *Logger) SetFlags(flag int) {
  390. l.mu.Lock()
  391. defer l.mu.Unlock()
  392. l.flag = flag
  393. }
  394. // Prefix returns the output prefix for the logger.
  395. func (l *Logger) Prefix() string {
  396. l.mu.Lock()
  397. defer l.mu.Unlock()
  398. return l.prefix
  399. }
  400. // SetPrefix sets the output prefix for the logger.
  401. func (l *Logger) SetPrefix(prefix string) {
  402. l.mu.Lock()
  403. defer l.mu.Unlock()
  404. l.prefix = prefix
  405. }
  406. // SetOutputLevel sets the output level for the logger.
  407. func (l *Logger) SetOutputLevel(lvl int) {
  408. l.mu.Lock()
  409. defer l.mu.Unlock()
  410. l.Level = lvl
  411. }
  412. func (l *Logger) OutputLevel() int {
  413. return l.Level
  414. }
  415. func (l *Logger) SetOutput(w io.Writer) {
  416. l.mu.Lock()
  417. defer l.mu.Unlock()
  418. l.out = w
  419. }
  420. // SetOutput sets the output destination for the standard logger.
  421. func SetOutput(w io.Writer) {
  422. Std.SetOutput(w)
  423. }
  424. // Flags returns the output flags for the standard logger.
  425. func Flags() int {
  426. return Std.Flags()
  427. }
  428. // SetFlags sets the output flags for the standard logger.
  429. func SetFlags(flag int) {
  430. Std.SetFlags(flag)
  431. }
  432. // Prefix returns the output prefix for the standard logger.
  433. func Prefix() string {
  434. return Std.Prefix()
  435. }
  436. // SetPrefix sets the output prefix for the standard logger.
  437. func SetPrefix(prefix string) {
  438. Std.SetPrefix(prefix)
  439. }
  440. func SetOutputLevel(lvl int) {
  441. Std.SetOutputLevel(lvl)
  442. }
  443. func OutputLevel() int {
  444. return Std.OutputLevel()
  445. }
  446. // -----------------------------------------
  447. // Print calls Output to print to the standard logger.
  448. // Arguments are handled in the manner of fmt.Print.
  449. func Print(v ...interface{}) {
  450. Std.Output("", Linfo, 2, fmt.Sprintln(v...))
  451. }
  452. // Printf calls Output to print to the standard logger.
  453. // Arguments are handled in the manner of fmt.Printf.
  454. func Printf(format string, v ...interface{}) {
  455. Std.Output("", Linfo, 2, fmt.Sprintf(format, v...))
  456. }
  457. // Println calls Output to print to the standard logger.
  458. // Arguments are handled in the manner of fmt.Println.
  459. func Println(v ...interface{}) {
  460. Std.Output("", Linfo, 2, fmt.Sprintln(v...))
  461. }
  462. // -----------------------------------------
  463. func Debugf(format string, v ...interface{}) {
  464. if Ldebug < Std.Level {
  465. return
  466. }
  467. Std.Output("", Ldebug, 2, fmt.Sprintf(format, v...))
  468. }
  469. func Debug(v ...interface{}) {
  470. if Ldebug < Std.Level {
  471. return
  472. }
  473. Std.Output("", Ldebug, 2, fmt.Sprintln(v...))
  474. }
  475. // -----------------------------------------
  476. func Infof(format string, v ...interface{}) {
  477. if Linfo < Std.Level {
  478. return
  479. }
  480. Std.Output("", Linfo, 2, fmt.Sprintf(format, v...))
  481. }
  482. func Info(v ...interface{}) {
  483. if Linfo < Std.Level {
  484. return
  485. }
  486. Std.Output("", Linfo, 2, fmt.Sprintln(v...))
  487. }
  488. // -----------------------------------------
  489. func Warnf(format string, v ...interface{}) {
  490. if Lwarn < Std.Level {
  491. return
  492. }
  493. Std.Output("", Lwarn, 2, fmt.Sprintf(format, v...))
  494. }
  495. func Warn(v ...interface{}) {
  496. if Lwarn < Std.Level {
  497. return
  498. }
  499. Std.Output("", Lwarn, 2, fmt.Sprintln(v...))
  500. }
  501. // -----------------------------------------
  502. func Errorf(format string, v ...interface{}) {
  503. if Lerror < Std.Level {
  504. return
  505. }
  506. Std.Output("", Lerror, 2, fmt.Sprintf(format, v...))
  507. }
  508. func Error(v ...interface{}) {
  509. if Lerror < Std.Level {
  510. return
  511. }
  512. Std.Output("", Lerror, 2, fmt.Sprintln(v...))
  513. }
  514. // -----------------------------------------
  515. // Fatal is equivalent to Print() followed by a call to os.Exit(1).
  516. func Fatal(v ...interface{}) {
  517. if Lfatal < Std.Level {
  518. return
  519. }
  520. Std.Output("", Lfatal, 2, fmt.Sprintln(v...))
  521. }
  522. // Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
  523. func Fatalf(format string, v ...interface{}) {
  524. if Lfatal < Std.Level {
  525. return
  526. }
  527. Std.Output("", Lfatal, 2, fmt.Sprintf(format, v...))
  528. }
  529. // -----------------------------------------
  530. // Panic is equivalent to Print() followed by a call to panic().
  531. func Panic(v ...interface{}) {
  532. if Lpanic < Std.Level {
  533. return
  534. }
  535. Std.Output("", Lpanic, 2, fmt.Sprintln(v...))
  536. }
  537. // Panicf is equivalent to Printf() followed by a call to panic().
  538. func Panicf(format string, v ...interface{}) {
  539. if Lpanic < Std.Level {
  540. return
  541. }
  542. Std.Output("", Lpanic, 2, fmt.Sprintf(format, v...))
  543. }
  544. // -----------------------------------------
  545. func Stack(v ...interface{}) {
  546. s := fmt.Sprint(v...)
  547. s += "\n"
  548. buf := make([]byte, 1024*1024)
  549. n := runtime.Stack(buf, true)
  550. s += string(buf[:n])
  551. s += "\n"
  552. Std.Output("", Lerror, 2, s)
  553. }
  554. // -----------------------------------------