log.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package log implements a simple logging package. It defines a type, Logger,
  5. // with methods for formatting output. It also has a predefined 'standard'
  6. // Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and
  7. // Panic[f|ln], which are easier to use than creating a Logger manually.
  8. // That logger writes to standard error and prints the date and time
  9. // of each logged message.
  10. // The Fatal functions call os.Exit(1) after writing the log message.
  11. // The Panic functions call panic after writing the log message.
  12. package log
  13. import (
  14. "fmt"
  15. "io"
  16. "os"
  17. "runtime"
  18. "sync"
  19. "time"
  20. )
  21. // These flags define which text to prefix to each log entry generated by the Logger.
  22. const (
  23. // Bits or'ed together to control what's printed. There is no control over the
  24. // order they appear (the order listed here) or the format they present (as
  25. // described in the comments). A colon appears after these items:
  26. // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
  27. Ldate = 1 << iota // the date: 2009/01/23
  28. Ltime // the time: 01:23:23
  29. Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
  30. Llongfile // full file name and line number: /a/b/c/d.go:23
  31. Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
  32. LstdFlags = Ldate | Ltime // initial values for the standard logger
  33. )
  34. // A Logger represents an active logging object that generates lines of
  35. // output to an io.Writer. Each logging operation makes a single call to
  36. // the Writer's Write method. A Logger can be used simultaneously from
  37. // multiple goroutines; it guarantees to serialize access to the Writer.
  38. type Logger struct {
  39. mu sync.Mutex // ensures atomic writes; protects the following fields
  40. prefix string // prefix to write at beginning of each line
  41. flag int // properties
  42. out io.Writer // destination for output
  43. buf []byte // for accumulating text to write
  44. }
  45. // New creates a new Logger. The out variable sets the
  46. // destination to which log data will be written.
  47. // The prefix appears at the beginning of each generated log line.
  48. // The flag argument defines the logging properties.
  49. func New(out io.Writer, prefix string, flag int) *Logger {
  50. return &Logger{out: out, prefix: prefix, flag: flag}
  51. }
  52. var std = New(os.Stderr, "", LstdFlags)
  53. // Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
  54. // Knows the buffer has capacity.
  55. func itoa(buf *[]byte, i int, wid int) {
  56. var u uint = uint(i)
  57. if u == 0 && wid <= 1 {
  58. *buf = append(*buf, '0')
  59. return
  60. }
  61. // Assemble decimal in reverse order.
  62. var b [32]byte
  63. bp := len(b)
  64. for ; u > 0 || wid > 0; u /= 10 {
  65. bp--
  66. wid--
  67. b[bp] = byte(u%10) + '0'
  68. }
  69. *buf = append(*buf, b[bp:]...)
  70. }
  71. func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) {
  72. *buf = append(*buf, l.prefix...)
  73. if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
  74. if l.flag&Ldate != 0 {
  75. year, month, day := t.Date()
  76. itoa(buf, year, 4)
  77. *buf = append(*buf, '/')
  78. itoa(buf, int(month), 2)
  79. *buf = append(*buf, '/')
  80. itoa(buf, day, 2)
  81. *buf = append(*buf, ' ')
  82. }
  83. if l.flag&(Ltime|Lmicroseconds) != 0 {
  84. hour, min, sec := t.Clock()
  85. itoa(buf, hour, 2)
  86. *buf = append(*buf, ':')
  87. itoa(buf, min, 2)
  88. *buf = append(*buf, ':')
  89. itoa(buf, sec, 2)
  90. if l.flag&Lmicroseconds != 0 {
  91. *buf = append(*buf, '.')
  92. itoa(buf, t.Nanosecond()/1e3, 6)
  93. }
  94. *buf = append(*buf, ' ')
  95. }
  96. }
  97. if l.flag&(Lshortfile|Llongfile) != 0 {
  98. if l.flag&Lshortfile != 0 {
  99. short := file
  100. for i := len(file) - 1; i > 0; i-- {
  101. if file[i] == '/' {
  102. short = file[i+1:]
  103. break
  104. }
  105. }
  106. file = short
  107. }
  108. *buf = append(*buf, file...)
  109. *buf = append(*buf, ':')
  110. itoa(buf, line, -1)
  111. *buf = append(*buf, ": "...)
  112. }
  113. }
  114. // Output writes the output for a logging event. The string s contains
  115. // the text to print after the prefix specified by the flags of the
  116. // Logger. A newline is appended if the last character of s is not
  117. // already a newline. Calldepth is used to recover the PC and is
  118. // provided for generality, although at the moment on all pre-defined
  119. // paths it will be 2.
  120. func (l *Logger) Output(calldepth int, s string) error {
  121. now := time.Now() // get this early.
  122. var file string
  123. var line int
  124. l.mu.Lock()
  125. defer l.mu.Unlock()
  126. if l.flag&(Lshortfile|Llongfile) != 0 {
  127. // release lock while getting caller info - it's expensive.
  128. l.mu.Unlock()
  129. var ok bool
  130. _, file, line, ok = runtime.Caller(calldepth)
  131. if !ok {
  132. file = "???"
  133. line = 0
  134. }
  135. l.mu.Lock()
  136. }
  137. l.buf = l.buf[:0]
  138. l.formatHeader(&l.buf, now, file, line)
  139. l.buf = append(l.buf, s...)
  140. if len(s) > 0 && s[len(s)-1] != '\n' {
  141. l.buf = append(l.buf, '\n')
  142. }
  143. _, err := l.out.Write(l.buf)
  144. return err
  145. }
  146. // Printf calls l.Output to print to the logger.
  147. // Arguments are handled in the manner of fmt.Printf.
  148. func (l *Logger) Printf(format string, v ...interface{}) {
  149. l.Output(2, fmt.Sprintf(format, v...))
  150. }
  151. // Print calls l.Output to print to the logger.
  152. // Arguments are handled in the manner of fmt.Print.
  153. func (l *Logger) Print(v ...interface{}) { l.Output(2, fmt.Sprint(v...)) }
  154. // Println calls l.Output to print to the logger.
  155. // Arguments are handled in the manner of fmt.Println.
  156. func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) }
  157. // Fatal is equivalent to l.Print() followed by a call to os.Exit(1).
  158. func (l *Logger) Fatal(v ...interface{}) {
  159. l.Output(2, fmt.Sprint(v...))
  160. os.Exit(1)
  161. }
  162. // Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).
  163. func (l *Logger) Fatalf(format string, v ...interface{}) {
  164. l.Output(2, fmt.Sprintf(format, v...))
  165. os.Exit(1)
  166. }
  167. // Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).
  168. func (l *Logger) Fatalln(v ...interface{}) {
  169. l.Output(2, fmt.Sprintln(v...))
  170. os.Exit(1)
  171. }
  172. // Panic is equivalent to l.Print() followed by a call to panic().
  173. func (l *Logger) Panic(v ...interface{}) {
  174. s := fmt.Sprint(v...)
  175. l.Output(2, s)
  176. panic(s)
  177. }
  178. // Panicf is equivalent to l.Printf() followed by a call to panic().
  179. func (l *Logger) Panicf(format string, v ...interface{}) {
  180. s := fmt.Sprintf(format, v...)
  181. l.Output(2, s)
  182. panic(s)
  183. }
  184. // Panicln is equivalent to l.Println() followed by a call to panic().
  185. func (l *Logger) Panicln(v ...interface{}) {
  186. s := fmt.Sprintln(v...)
  187. l.Output(2, s)
  188. panic(s)
  189. }
  190. // Flags returns the output flags for the logger.
  191. func (l *Logger) Flags() int {
  192. l.mu.Lock()
  193. defer l.mu.Unlock()
  194. return l.flag
  195. }
  196. // SetFlags sets the output flags for the logger.
  197. func (l *Logger) SetFlags(flag int) {
  198. l.mu.Lock()
  199. defer l.mu.Unlock()
  200. l.flag = flag
  201. }
  202. // Prefix returns the output prefix for the logger.
  203. func (l *Logger) Prefix() string {
  204. l.mu.Lock()
  205. defer l.mu.Unlock()
  206. return l.prefix
  207. }
  208. // SetPrefix sets the output prefix for the logger.
  209. func (l *Logger) SetPrefix(prefix string) {
  210. l.mu.Lock()
  211. defer l.mu.Unlock()
  212. l.prefix = prefix
  213. }
  214. // SetOutput sets the output destination for the standard logger.
  215. func SetOutput(w io.Writer) {
  216. std.mu.Lock()
  217. defer std.mu.Unlock()
  218. std.out = w
  219. }
  220. // Flags returns the output flags for the standard logger.
  221. func Flags() int {
  222. return std.Flags()
  223. }
  224. // SetFlags sets the output flags for the standard logger.
  225. func SetFlags(flag int) {
  226. std.SetFlags(flag)
  227. }
  228. // Prefix returns the output prefix for the standard logger.
  229. func Prefix() string {
  230. return std.Prefix()
  231. }
  232. // SetPrefix sets the output prefix for the standard logger.
  233. func SetPrefix(prefix string) {
  234. std.SetPrefix(prefix)
  235. }
  236. // These functions write to the standard logger.
  237. // Print calls Output to print to the standard logger.
  238. // Arguments are handled in the manner of fmt.Print.
  239. func Print(v ...interface{}) {
  240. std.Output(2, fmt.Sprint(v...))
  241. }
  242. // Printf calls Output to print to the standard logger.
  243. // Arguments are handled in the manner of fmt.Printf.
  244. func Printf(format string, v ...interface{}) {
  245. std.Output(2, fmt.Sprintf(format, v...))
  246. }
  247. // Println calls Output to print to the standard logger.
  248. // Arguments are handled in the manner of fmt.Println.
  249. func Println(v ...interface{}) {
  250. std.Output(2, fmt.Sprintln(v...))
  251. }
  252. // Fatal is equivalent to Print() followed by a call to os.Exit(1).
  253. func Fatal(v ...interface{}) {
  254. std.Output(2, fmt.Sprint(v...))
  255. os.Exit(1)
  256. }
  257. // Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
  258. func Fatalf(format string, v ...interface{}) {
  259. std.Output(2, fmt.Sprintf(format, v...))
  260. os.Exit(1)
  261. }
  262. // Fatalln is equivalent to Println() followed by a call to os.Exit(1).
  263. func Fatalln(v ...interface{}) {
  264. std.Output(2, fmt.Sprintln(v...))
  265. os.Exit(1)
  266. }
  267. // Panic is equivalent to Print() followed by a call to panic().
  268. func Panic(v ...interface{}) {
  269. s := fmt.Sprint(v...)
  270. std.Output(2, s)
  271. panic(s)
  272. }
  273. // Panicf is equivalent to Printf() followed by a call to panic().
  274. func Panicf(format string, v ...interface{}) {
  275. s := fmt.Sprintf(format, v...)
  276. std.Output(2, s)
  277. panic(s)
  278. }
  279. // Panicln is equivalent to Println() followed by a call to panic().
  280. func Panicln(v ...interface{}) {
  281. s := fmt.Sprintln(v...)
  282. std.Output(2, s)
  283. panic(s)
  284. }