types.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package log
  2. import (
  3. "encoding/json"
  4. "strings"
  5. )
  6. // Level is a well-known log level, as defined below
  7. type Level int
  8. // Well known log levels
  9. const (
  10. TraceLevel Level = iota
  11. DebugLevel
  12. InfoLevel
  13. WarnLevel
  14. ErrorLevel
  15. FatalLevel
  16. )
  17. func (l Level) String() string {
  18. switch l {
  19. case TraceLevel:
  20. return "TRACE"
  21. case DebugLevel:
  22. return "DEBUG"
  23. case InfoLevel:
  24. return "INFO"
  25. case WarnLevel:
  26. return "WARN"
  27. case ErrorLevel:
  28. return "ERROR"
  29. case FatalLevel:
  30. return "FATAL"
  31. }
  32. return "unknown"
  33. }
  34. func (l Level) MarshalJSON() ([]byte, error) {
  35. return json.Marshal(l.String())
  36. }
  37. // ToLevel converts a string to a Level. It returns InfoLevel if the string
  38. // does not match any known log levels.
  39. func ToLevel(s string) Level {
  40. switch strings.ToUpper(s) {
  41. case "TRACE":
  42. return TraceLevel
  43. case "DEBUG":
  44. return DebugLevel
  45. case "INFO":
  46. return InfoLevel
  47. case "WARN", "WARNING":
  48. return WarnLevel
  49. case "ERROR":
  50. return ErrorLevel
  51. default:
  52. return InfoLevel
  53. }
  54. }
  55. // Format is a well-known log format
  56. type Format int
  57. // Log formats
  58. const (
  59. TextFormat Format = iota
  60. JSONFormat
  61. )
  62. func (f Format) String() string {
  63. switch f {
  64. case TextFormat:
  65. return "text"
  66. case JSONFormat:
  67. return "json"
  68. }
  69. return "unknown"
  70. }
  71. // ToFormat converts a string to a Format. It returns TextFormat if the string
  72. // does not match any known log formats.
  73. func ToFormat(s string) Format {
  74. switch strings.ToLower(s) {
  75. case "text":
  76. return TextFormat
  77. case "json":
  78. return JSONFormat
  79. default:
  80. return TextFormat
  81. }
  82. }
  83. type Ctx interface {
  84. Context() map[string]any
  85. }
  86. type fieldsCtx map[string]any
  87. func (f fieldsCtx) Context() map[string]any {
  88. return f
  89. }
  90. func NewCtx(fields map[string]any) Ctx {
  91. return fieldsCtx(fields)
  92. }
  93. type levelOverride struct {
  94. value any
  95. level Level
  96. }