types.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. case "FATAL":
  53. return FatalLevel
  54. default:
  55. return InfoLevel
  56. }
  57. }
  58. // Format is a well-known log format
  59. type Format int
  60. // Log formats
  61. const (
  62. TextFormat Format = iota
  63. JSONFormat
  64. )
  65. func (f Format) String() string {
  66. switch f {
  67. case TextFormat:
  68. return "text"
  69. case JSONFormat:
  70. return "json"
  71. }
  72. return "unknown"
  73. }
  74. // ToFormat converts a string to a Format. It returns TextFormat if the string
  75. // does not match any known log formats.
  76. func ToFormat(s string) Format {
  77. switch strings.ToLower(s) {
  78. case "text":
  79. return TextFormat
  80. case "json":
  81. return JSONFormat
  82. default:
  83. return TextFormat
  84. }
  85. }
  86. // Contexter allows structs to export a key-value pairs in the form of a Context
  87. type Contexter interface {
  88. Context() Context
  89. }
  90. // Context represents an object's state in the form of key-value pairs
  91. type Context map[string]any
  92. // Merge merges other into this context
  93. func (c Context) Merge(other Context) {
  94. for k, v := range other {
  95. c[k] = v
  96. }
  97. }
  98. type levelOverride struct {
  99. value string
  100. level Level
  101. }