logger.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. NumLevels
  24. )
  25. const (
  26. DefaultFlags = log.Ltime
  27. DebugFlags = log.Ltime | log.Ldate | log.Lmicroseconds | log.Lshortfile
  28. )
  29. // A MessageHandler is called with the log level and message text.
  30. type MessageHandler func(l LogLevel, msg string)
  31. type Logger interface {
  32. AddHandler(level LogLevel, h MessageHandler)
  33. SetFlags(flag int)
  34. SetPrefix(prefix string)
  35. Debugln(vals ...interface{})
  36. Debugf(format string, vals ...interface{})
  37. Verboseln(vals ...interface{})
  38. Verbosef(format string, vals ...interface{})
  39. Infoln(vals ...interface{})
  40. Infof(format string, vals ...interface{})
  41. Warnln(vals ...interface{})
  42. Warnf(format string, vals ...interface{})
  43. ShouldDebug(facility string) bool
  44. SetDebug(facility string, enabled bool)
  45. IsTraced(facility string) 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]struct{} // only facility names with debugging enabled
  55. traces string
  56. mut sync.Mutex
  57. }
  58. // DefaultLogger logs to standard output with a time prefix.
  59. var DefaultLogger = New()
  60. func New() Logger {
  61. if os.Getenv("LOGGER_DISCARD") != "" {
  62. // Hack to completely disable logging, for example when running
  63. // benchmarks.
  64. return newLogger(ioutil.Discard)
  65. }
  66. return newLogger(controlStripper{os.Stdout})
  67. }
  68. func newLogger(w io.Writer) Logger {
  69. return &logger{
  70. logger: log.New(w, "", DefaultFlags),
  71. traces: os.Getenv("STTRACE"),
  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. // ShouldDebug returns true if the given facility has debugging enabled.
  169. func (l *logger) ShouldDebug(facility string) bool {
  170. l.mut.Lock()
  171. _, res := l.debug[facility]
  172. l.mut.Unlock()
  173. return res
  174. }
  175. // SetDebug enabled or disables debugging for the given facility name.
  176. func (l *logger) SetDebug(facility string, enabled bool) {
  177. l.mut.Lock()
  178. defer l.mut.Unlock()
  179. if _, ok := l.debug[facility]; enabled && !ok {
  180. l.SetFlags(DebugFlags)
  181. l.debug[facility] = struct{}{}
  182. } else if !enabled && ok {
  183. delete(l.debug, facility)
  184. if len(l.debug) == 0 {
  185. l.SetFlags(DefaultFlags)
  186. }
  187. }
  188. }
  189. // IsTraced returns whether the facility name is contained in STTRACE.
  190. func (l *logger) IsTraced(facility string) bool {
  191. return strings.Contains(l.traces, facility) || l.traces == "all"
  192. }
  193. // FacilityDebugging returns the set of facilities that have debugging
  194. // enabled.
  195. func (l *logger) FacilityDebugging() []string {
  196. enabled := make([]string, 0, len(l.debug))
  197. l.mut.Lock()
  198. for facility := range l.debug {
  199. enabled = append(enabled, facility)
  200. }
  201. l.mut.Unlock()
  202. return enabled
  203. }
  204. // Facilities returns the currently known set of facilities and their
  205. // descriptions.
  206. func (l *logger) Facilities() map[string]string {
  207. l.mut.Lock()
  208. res := make(map[string]string, len(l.facilities))
  209. for facility, descr := range l.facilities {
  210. res[facility] = descr
  211. }
  212. l.mut.Unlock()
  213. return res
  214. }
  215. // NewFacility returns a new logger bound to the named facility.
  216. func (l *logger) NewFacility(facility, description string) Logger {
  217. l.SetDebug(facility, l.IsTraced(facility))
  218. l.mut.Lock()
  219. l.facilities[facility] = description
  220. l.mut.Unlock()
  221. return &facilityLogger{
  222. logger: l,
  223. facility: facility,
  224. }
  225. }
  226. // A facilityLogger is a regular logger but bound to a facility name. The
  227. // Debugln and Debugf methods are no-ops unless debugging has been enabled for
  228. // this facility on the parent logger.
  229. type facilityLogger struct {
  230. *logger
  231. facility string
  232. }
  233. // Debugln logs a line with a DEBUG prefix.
  234. func (l *facilityLogger) Debugln(vals ...interface{}) {
  235. if !l.ShouldDebug(l.facility) {
  236. return
  237. }
  238. l.logger.debugln(3, vals...)
  239. }
  240. // Debugf logs a formatted line with a DEBUG prefix.
  241. func (l *facilityLogger) Debugf(format string, vals ...interface{}) {
  242. if !l.ShouldDebug(l.facility) {
  243. return
  244. }
  245. l.logger.debugf(3, format, vals...)
  246. }
  247. // A Recorder keeps a size limited record of log events.
  248. type Recorder interface {
  249. Since(t time.Time) []Line
  250. Clear()
  251. }
  252. type recorder struct {
  253. lines []Line
  254. initial int
  255. mut sync.Mutex
  256. }
  257. // A Line represents a single log entry.
  258. type Line struct {
  259. When time.Time `json:"when"`
  260. Message string `json:"message"`
  261. Level LogLevel `json:"level"`
  262. }
  263. func NewRecorder(l Logger, level LogLevel, size, initial int) Recorder {
  264. r := &recorder{
  265. lines: make([]Line, 0, size),
  266. initial: initial,
  267. }
  268. l.AddHandler(level, r.append)
  269. return r
  270. }
  271. func (r *recorder) Since(t time.Time) []Line {
  272. r.mut.Lock()
  273. defer r.mut.Unlock()
  274. res := r.lines
  275. for i := 0; i < len(res); i++ {
  276. if res[i].When.After(t) {
  277. // We must copy the result as r.lines can be mutated as soon as the lock
  278. // is released.
  279. res = res[i:]
  280. cp := make([]Line, len(res))
  281. copy(cp, res)
  282. return cp
  283. }
  284. }
  285. return nil
  286. }
  287. func (r *recorder) Clear() {
  288. r.mut.Lock()
  289. r.lines = r.lines[:0]
  290. r.mut.Unlock()
  291. }
  292. func (r *recorder) append(l LogLevel, msg string) {
  293. line := Line{
  294. When: time.Now(),
  295. Message: msg,
  296. Level: l,
  297. }
  298. r.mut.Lock()
  299. defer r.mut.Unlock()
  300. if len(r.lines) == cap(r.lines) {
  301. if r.initial > 0 {
  302. // Shift all lines one step to the left, keeping the "initial" first intact.
  303. copy(r.lines[r.initial+1:], r.lines[r.initial+2:])
  304. } else {
  305. copy(r.lines, r.lines[1:])
  306. }
  307. // Add the new one at the end
  308. r.lines[len(r.lines)-1] = line
  309. return
  310. }
  311. r.lines = append(r.lines, line)
  312. if len(r.lines) == r.initial {
  313. r.lines = append(r.lines, Line{time.Now(), "...", l})
  314. }
  315. }
  316. // controlStripper is a Writer that replaces control characters
  317. // with spaces.
  318. type controlStripper struct {
  319. io.Writer
  320. }
  321. func (s controlStripper) Write(data []byte) (int, error) {
  322. for i, b := range data {
  323. if b == '\n' || b == '\r' {
  324. // Newlines are OK
  325. continue
  326. }
  327. if b < 32 {
  328. // Characters below 32 are control characters
  329. data[i] = ' '
  330. }
  331. }
  332. return s.Writer.Write(data)
  333. }