logger.go 9.3 KB

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