logger.go 9.6 KB

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