types.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. // MarshalJSON converts a level to a JSON string
  35. func (l Level) MarshalJSON() ([]byte, error) {
  36. return json.Marshal(l.String())
  37. }
  38. // ToLevel converts a string to a Level. It returns InfoLevel if the string
  39. // does not match any known log levels.
  40. func ToLevel(s string) Level {
  41. switch strings.ToUpper(s) {
  42. case "TRACE":
  43. return TraceLevel
  44. case "DEBUG":
  45. return DebugLevel
  46. case "INFO":
  47. return InfoLevel
  48. case "WARN", "WARNING":
  49. return WarnLevel
  50. case "ERROR":
  51. return ErrorLevel
  52. default:
  53. return InfoLevel
  54. }
  55. }
  56. // Format is a well-known log format
  57. type Format int
  58. // Log formats
  59. const (
  60. TextFormat Format = iota
  61. JSONFormat
  62. )
  63. func (f Format) String() string {
  64. switch f {
  65. case TextFormat:
  66. return "text"
  67. case JSONFormat:
  68. return "json"
  69. }
  70. return "unknown"
  71. }
  72. // ToFormat converts a string to a Format. It returns TextFormat if the string
  73. // does not match any known log formats.
  74. func ToFormat(s string) Format {
  75. switch strings.ToLower(s) {
  76. case "text":
  77. return TextFormat
  78. case "json":
  79. return JSONFormat
  80. default:
  81. return TextFormat
  82. }
  83. }
  84. // Contexter allows structs to export a key-value pairs in the form of a Context
  85. type Contexter interface {
  86. Context() Context
  87. }
  88. // Context represents an object's state in the form of key-value pairs
  89. type Context map[string]any
  90. type levelOverride struct {
  91. value any
  92. level Level
  93. }