log.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. This Source Code Form is subject to the terms of the Mozilla Public
  3. License, v. 2.0. If a copy of the MPL was not distributed with this
  4. file, You can obtain one at https://mozilla.org/MPL/2.0/.
  5. */
  6. package internal
  7. import (
  8. "log"
  9. "os"
  10. )
  11. type LogLevel int
  12. const (
  13. LogLevelSilent LogLevel = iota - 4
  14. LogLevelFatal
  15. LogLevelError
  16. LogLevelWarn
  17. LogLevelPrint
  18. LogLevelInfo
  19. LogLevelDebug
  20. )
  21. func NewLogger() *Logger {
  22. return &Logger{}
  23. }
  24. // TODO use separate debug logger with line number output
  25. type Logger struct {
  26. parent *Logger
  27. level LogLevel
  28. base string
  29. }
  30. func (l *Logger) addBase(format string) string {
  31. if l.parent == nil {
  32. return format
  33. }
  34. return l.parent.addBase(format)
  35. }
  36. func (l *Logger) Level(level LogLevel) {
  37. l.level = level
  38. }
  39. func (l *Logger) Push(str string) *Logger {
  40. return &Logger{parent: l, base: str}
  41. }
  42. func (l *Logger) Print(format string, msg ...any) {
  43. l.logAs(LogLevelPrint, format, msg...)
  44. }
  45. func (l *Logger) Fatal(format string, msg ...any) {
  46. l.logAs(LogLevelFatal, l.addBase(format), msg...)
  47. os.Exit(1)
  48. }
  49. func (l *Logger) Error(format string, msg ...any) {
  50. l.logAs(LogLevelError, l.addBase(format), msg...)
  51. }
  52. func (l *Logger) Warn(format string, msg ...any) {
  53. l.logAs(LogLevelWarn, l.addBase(format), msg...)
  54. }
  55. func (l *Logger) Info(format string, msg ...any) {
  56. l.logAs(LogLevelInfo, l.addBase(format), msg...)
  57. }
  58. func (l *Logger) Debug(format string, msg ...any) {
  59. l.logAs(LogLevelDebug, l.addBase(format), msg...)
  60. }
  61. func (l *Logger) logAs(
  62. level LogLevel,
  63. format string,
  64. msg ...any,
  65. ) {
  66. if level > l.level {
  67. return
  68. }
  69. var pfx string
  70. switch level {
  71. case LogLevelFatal:
  72. pfx = "FATAL"
  73. case LogLevelError:
  74. pfx = "ERROR"
  75. case LogLevelWarn:
  76. pfx = "Warn"
  77. case LogLevelInfo:
  78. pfx = "info"
  79. case LogLevelDebug:
  80. pfx = "debug"
  81. }
  82. log.Printf(pfx+": "+format, msg...)
  83. }