logger.go 9.0 KB

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