logger.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package badger
  6. import (
  7. "log"
  8. "os"
  9. )
  10. // Logger is implemented by any logging system that is used for standard logs.
  11. type Logger interface {
  12. Errorf(string, ...interface{})
  13. Warningf(string, ...interface{})
  14. Infof(string, ...interface{})
  15. Debugf(string, ...interface{})
  16. }
  17. // Errorf logs an ERROR log message to the logger specified in opts or to the
  18. // global logger if no logger is specified in opts.
  19. func (opt *Options) Errorf(format string, v ...interface{}) {
  20. if opt.Logger == nil {
  21. return
  22. }
  23. opt.Logger.Errorf(format, v...)
  24. }
  25. // Infof logs an INFO message to the logger specified in opts.
  26. func (opt *Options) Infof(format string, v ...interface{}) {
  27. if opt.Logger == nil {
  28. return
  29. }
  30. opt.Logger.Infof(format, v...)
  31. }
  32. // Warningf logs a WARNING message to the logger specified in opts.
  33. func (opt *Options) Warningf(format string, v ...interface{}) {
  34. if opt.Logger == nil {
  35. return
  36. }
  37. opt.Logger.Warningf(format, v...)
  38. }
  39. // Debugf logs a DEBUG message to the logger specified in opts.
  40. func (opt *Options) Debugf(format string, v ...interface{}) {
  41. if opt.Logger == nil {
  42. return
  43. }
  44. opt.Logger.Debugf(format, v...)
  45. }
  46. type loggingLevel int
  47. const (
  48. DEBUG loggingLevel = iota
  49. INFO
  50. WARNING
  51. ERROR
  52. )
  53. type defaultLog struct {
  54. *log.Logger
  55. level loggingLevel
  56. }
  57. func defaultLogger(level loggingLevel) *defaultLog {
  58. return &defaultLog{Logger: log.New(os.Stderr, "badger ", log.LstdFlags), level: level}
  59. }
  60. func (l *defaultLog) Errorf(f string, v ...interface{}) {
  61. if l.level <= ERROR {
  62. l.Printf("ERROR: "+f, v...)
  63. }
  64. }
  65. func (l *defaultLog) Warningf(f string, v ...interface{}) {
  66. if l.level <= WARNING {
  67. l.Printf("WARNING: "+f, v...)
  68. }
  69. }
  70. func (l *defaultLog) Infof(f string, v ...interface{}) {
  71. if l.level <= INFO {
  72. l.Printf("INFO: "+f, v...)
  73. }
  74. }
  75. func (l *defaultLog) Debugf(f string, v ...interface{}) {
  76. if l.level <= DEBUG {
  77. l.Printf("DEBUG: "+f, v...)
  78. }
  79. }