logger.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. // Copyright (C) 2014 Jakob Borg. All rights reserved. Use of this source code
  2. // is governed by an MIT-style license that can be found in the LICENSE file.
  3. // Package logger implements a standardized logger with callback functionality
  4. package logger
  5. import (
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "os"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. // This package uses stdlib sync as it may be used to debug syncthing/lib/sync
  16. // and that would cause an implosion of the universe.
  17. type LogLevel int
  18. const (
  19. LevelDebug LogLevel = iota
  20. LevelVerbose
  21. LevelInfo
  22. LevelWarn
  23. LevelFatal
  24. NumLevels
  25. )
  26. const (
  27. DefaultFlags = log.Ltime
  28. DebugFlags = log.Ltime | log.Ldate | log.Lmicroseconds | log.Lshortfile
  29. )
  30. // A MessageHandler is called with the log level and message text.
  31. type MessageHandler func(l LogLevel, msg string)
  32. type Logger interface {
  33. AddHandler(level LogLevel, h MessageHandler)
  34. SetFlags(flag int)
  35. SetPrefix(prefix string)
  36. Debugln(vals ...interface{})
  37. Debugf(format string, vals ...interface{})
  38. Verboseln(vals ...interface{})
  39. Verbosef(format string, vals ...interface{})
  40. Infoln(vals ...interface{})
  41. Infof(format string, vals ...interface{})
  42. Warnln(vals ...interface{})
  43. Warnf(format string, vals ...interface{})
  44. Fatalln(vals ...interface{})
  45. Fatalf(format string, vals ...interface{})
  46. ShouldDebug(facility string) bool
  47. SetDebug(facility string, enabled bool)
  48. Facilities() map[string]string
  49. FacilityDebugging() []string
  50. NewFacility(facility, description string) Logger
  51. }
  52. type logger struct {
  53. logger *log.Logger
  54. handlers [NumLevels][]MessageHandler
  55. facilities map[string]string // facility name => description
  56. debug map[string]struct{} // only facility names with debugging enabled
  57. mut sync.Mutex
  58. }
  59. // DefaultLogger logs to standard output with a time prefix.
  60. var DefaultLogger = New()
  61. func New() Logger {
  62. if os.Getenv("LOGGER_DISCARD") != "" {
  63. // Hack to completely disable logging, for example when running
  64. // benchmarks.
  65. return newLogger(ioutil.Discard)
  66. }
  67. return newLogger(controlStripper{os.Stdout})
  68. }
  69. func newLogger(w io.Writer) Logger {
  70. return &logger{
  71. logger: log.New(w, "", DefaultFlags),
  72. facilities: make(map[string]string),
  73. debug: make(map[string]struct{}),
  74. }
  75. }
  76. // AddHandler registers a new MessageHandler to receive messages with the
  77. // specified log level or above.
  78. func (l *logger) AddHandler(level LogLevel, h MessageHandler) {
  79. l.mut.Lock()
  80. defer l.mut.Unlock()
  81. l.handlers[level] = append(l.handlers[level], h)
  82. }
  83. // See log.SetFlags
  84. func (l *logger) SetFlags(flag int) {
  85. l.logger.SetFlags(flag)
  86. }
  87. // See log.SetPrefix
  88. func (l *logger) SetPrefix(prefix string) {
  89. l.logger.SetPrefix(prefix)
  90. }
  91. func (l *logger) callHandlers(level LogLevel, s string) {
  92. for ll := LevelDebug; ll <= level; ll++ {
  93. for _, h := range l.handlers[ll] {
  94. h(level, strings.TrimSpace(s))
  95. }
  96. }
  97. }
  98. // Debugln logs a line with a DEBUG prefix.
  99. func (l *logger) Debugln(vals ...interface{}) {
  100. l.debugln(3, vals...)
  101. }
  102. func (l *logger) debugln(level int, vals ...interface{}) {
  103. s := fmt.Sprintln(vals...)
  104. l.mut.Lock()
  105. defer l.mut.Unlock()
  106. l.logger.Output(level, "DEBUG: "+s)
  107. l.callHandlers(LevelDebug, s)
  108. }
  109. // Debugf logs a formatted line with a DEBUG prefix.
  110. func (l *logger) Debugf(format string, vals ...interface{}) {
  111. l.debugf(3, format, vals...)
  112. }
  113. func (l *logger) debugf(level int, format string, vals ...interface{}) {
  114. s := fmt.Sprintf(format, vals...)
  115. l.mut.Lock()
  116. defer l.mut.Unlock()
  117. l.logger.Output(level, "DEBUG: "+s)
  118. l.callHandlers(LevelDebug, s)
  119. }
  120. // Infoln logs a line with a VERBOSE prefix.
  121. func (l *logger) Verboseln(vals ...interface{}) {
  122. s := fmt.Sprintln(vals...)
  123. l.mut.Lock()
  124. defer l.mut.Unlock()
  125. l.logger.Output(2, "VERBOSE: "+s)
  126. l.callHandlers(LevelVerbose, s)
  127. }
  128. // Infof logs a formatted line with a VERBOSE prefix.
  129. func (l *logger) Verbosef(format string, vals ...interface{}) {
  130. s := fmt.Sprintf(format, vals...)
  131. l.mut.Lock()
  132. defer l.mut.Unlock()
  133. l.logger.Output(2, "VERBOSE: "+s)
  134. l.callHandlers(LevelVerbose, s)
  135. }
  136. // Infoln logs a line with an INFO prefix.
  137. func (l *logger) Infoln(vals ...interface{}) {
  138. s := fmt.Sprintln(vals...)
  139. l.mut.Lock()
  140. defer l.mut.Unlock()
  141. l.logger.Output(2, "INFO: "+s)
  142. l.callHandlers(LevelInfo, s)
  143. }
  144. // Infof logs a formatted line with an INFO prefix.
  145. func (l *logger) Infof(format string, vals ...interface{}) {
  146. s := fmt.Sprintf(format, vals...)
  147. l.mut.Lock()
  148. defer l.mut.Unlock()
  149. l.logger.Output(2, "INFO: "+s)
  150. l.callHandlers(LevelInfo, s)
  151. }
  152. // Warnln logs a formatted line with a WARNING prefix.
  153. func (l *logger) Warnln(vals ...interface{}) {
  154. s := fmt.Sprintln(vals...)
  155. l.mut.Lock()
  156. defer l.mut.Unlock()
  157. l.logger.Output(2, "WARNING: "+s)
  158. l.callHandlers(LevelWarn, s)
  159. }
  160. // Warnf logs a formatted line with a WARNING prefix.
  161. func (l *logger) Warnf(format string, vals ...interface{}) {
  162. s := fmt.Sprintf(format, vals...)
  163. l.mut.Lock()
  164. defer l.mut.Unlock()
  165. l.logger.Output(2, "WARNING: "+s)
  166. l.callHandlers(LevelWarn, s)
  167. }
  168. // Fatalln logs a line with a FATAL prefix and exits the process with exit
  169. // code 1.
  170. func (l *logger) Fatalln(vals ...interface{}) {
  171. s := fmt.Sprintln(vals...)
  172. l.mut.Lock()
  173. defer l.mut.Unlock()
  174. l.logger.Output(2, "FATAL: "+s)
  175. l.callHandlers(LevelFatal, s)
  176. os.Exit(1)
  177. }
  178. // Fatalf logs a formatted line with a FATAL prefix and exits the process with
  179. // exit code 1.
  180. func (l *logger) Fatalf(format string, vals ...interface{}) {
  181. s := fmt.Sprintf(format, vals...)
  182. l.mut.Lock()
  183. defer l.mut.Unlock()
  184. l.logger.Output(2, "FATAL: "+s)
  185. l.callHandlers(LevelFatal, s)
  186. os.Exit(1)
  187. }
  188. // ShouldDebug returns true if the given facility has debugging enabled.
  189. func (l *logger) ShouldDebug(facility string) bool {
  190. l.mut.Lock()
  191. _, res := l.debug[facility]
  192. l.mut.Unlock()
  193. return res
  194. }
  195. // SetDebug enabled or disables debugging for the given facility name.
  196. func (l *logger) SetDebug(facility string, enabled bool) {
  197. l.mut.Lock()
  198. defer l.mut.Unlock()
  199. if _, ok := l.debug[facility]; enabled && !ok {
  200. l.SetFlags(DebugFlags)
  201. l.debug[facility] = struct{}{}
  202. } else if !enabled && ok {
  203. delete(l.debug, facility)
  204. if len(l.debug) == 0 {
  205. l.SetFlags(DefaultFlags)
  206. }
  207. }
  208. }
  209. // FacilityDebugging returns the set of facilities that have debugging
  210. // enabled.
  211. func (l *logger) FacilityDebugging() []string {
  212. enabled := make([]string, 0, len(l.debug))
  213. l.mut.Lock()
  214. for facility := range l.debug {
  215. enabled = append(enabled, facility)
  216. }
  217. l.mut.Unlock()
  218. return enabled
  219. }
  220. // Facilities returns the currently known set of facilities and their
  221. // descriptions.
  222. func (l *logger) Facilities() map[string]string {
  223. l.mut.Lock()
  224. res := make(map[string]string, len(l.facilities))
  225. for facility, descr := range l.facilities {
  226. res[facility] = descr
  227. }
  228. l.mut.Unlock()
  229. return res
  230. }
  231. // NewFacility returns a new logger bound to the named facility.
  232. func (l *logger) NewFacility(facility, description string) Logger {
  233. l.mut.Lock()
  234. l.facilities[facility] = description
  235. l.mut.Unlock()
  236. return &facilityLogger{
  237. logger: l,
  238. facility: facility,
  239. }
  240. }
  241. // A facilityLogger is a regular logger but bound to a facility name. The
  242. // Debugln and Debugf methods are no-ops unless debugging has been enabled for
  243. // this facility on the parent logger.
  244. type facilityLogger struct {
  245. *logger
  246. facility string
  247. }
  248. // Debugln logs a line with a DEBUG prefix.
  249. func (l *facilityLogger) Debugln(vals ...interface{}) {
  250. if !l.ShouldDebug(l.facility) {
  251. return
  252. }
  253. l.logger.debugln(3, vals...)
  254. }
  255. // Debugf logs a formatted line with a DEBUG prefix.
  256. func (l *facilityLogger) Debugf(format string, vals ...interface{}) {
  257. if !l.ShouldDebug(l.facility) {
  258. return
  259. }
  260. l.logger.debugf(3, format, vals...)
  261. }
  262. // A Recorder keeps a size limited record of log events.
  263. type Recorder interface {
  264. Since(t time.Time) []Line
  265. Clear()
  266. }
  267. type recorder struct {
  268. lines []Line
  269. initial int
  270. mut sync.Mutex
  271. }
  272. // A Line represents a single log entry.
  273. type Line struct {
  274. When time.Time `json:"when"`
  275. Message string `json:"message"`
  276. Level LogLevel `json:"level"`
  277. }
  278. func NewRecorder(l Logger, level LogLevel, size, initial int) Recorder {
  279. r := &recorder{
  280. lines: make([]Line, 0, size),
  281. initial: initial,
  282. }
  283. l.AddHandler(level, r.append)
  284. return r
  285. }
  286. func (r *recorder) Since(t time.Time) []Line {
  287. r.mut.Lock()
  288. defer r.mut.Unlock()
  289. res := r.lines
  290. for i := 0; i < len(res); i++ {
  291. if res[i].When.After(t) {
  292. // We must copy the result as r.lines can be mutated as soon as the lock
  293. // is released.
  294. res = res[i:]
  295. cp := make([]Line, len(res))
  296. copy(cp, res)
  297. return cp
  298. }
  299. }
  300. return nil
  301. }
  302. func (r *recorder) Clear() {
  303. r.mut.Lock()
  304. r.lines = r.lines[:0]
  305. r.mut.Unlock()
  306. }
  307. func (r *recorder) append(l LogLevel, msg string) {
  308. line := Line{
  309. When: time.Now(),
  310. Message: msg,
  311. Level: l,
  312. }
  313. r.mut.Lock()
  314. defer r.mut.Unlock()
  315. if len(r.lines) == cap(r.lines) {
  316. if r.initial > 0 {
  317. // Shift all lines one step to the left, keeping the "initial" first intact.
  318. copy(r.lines[r.initial+1:], r.lines[r.initial+2:])
  319. } else {
  320. copy(r.lines, r.lines[1:])
  321. }
  322. // Add the new one at the end
  323. r.lines[len(r.lines)-1] = line
  324. return
  325. }
  326. r.lines = append(r.lines, line)
  327. if len(r.lines) == r.initial {
  328. r.lines = append(r.lines, Line{time.Now(), "...", l})
  329. }
  330. }
  331. // controlStripper is a Writer that replaces control characters
  332. // with spaces.
  333. type controlStripper struct {
  334. io.Writer
  335. }
  336. func (s controlStripper) Write(data []byte) (int, error) {
  337. for i, b := range data {
  338. if b == '\n' || b == '\r' {
  339. // Newlines are OK
  340. continue
  341. }
  342. if b < 32 {
  343. // Characters below 32 are control characters
  344. data[i] = ' '
  345. }
  346. }
  347. return s.Writer.Write(data)
  348. }