You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

level.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package log
  4. import (
  5. "bytes"
  6. "strings"
  7. "code.gitea.io/gitea/modules/json"
  8. )
  9. // Level is the level of the logger
  10. type Level int
  11. const (
  12. UNDEFINED Level = iota
  13. TRACE
  14. DEBUG
  15. INFO
  16. WARN
  17. ERROR
  18. FATAL
  19. NONE
  20. )
  21. const CRITICAL = ERROR // most logger frameworks doesn't support CRITICAL, and it doesn't seem useful
  22. var toString = map[Level]string{
  23. UNDEFINED: "undefined",
  24. TRACE: "trace",
  25. DEBUG: "debug",
  26. INFO: "info",
  27. WARN: "warn",
  28. ERROR: "error",
  29. FATAL: "fatal",
  30. NONE: "none",
  31. }
  32. var toLevel = map[string]Level{
  33. "undefined": UNDEFINED,
  34. "trace": TRACE,
  35. "debug": DEBUG,
  36. "info": INFO,
  37. "warn": WARN,
  38. "warning": WARN,
  39. "error": ERROR,
  40. "fatal": FATAL,
  41. "none": NONE,
  42. }
  43. var levelToColor = map[Level][]ColorAttribute{
  44. TRACE: {Bold, FgCyan},
  45. DEBUG: {Bold, FgBlue},
  46. INFO: {Bold, FgGreen},
  47. WARN: {Bold, FgYellow},
  48. ERROR: {Bold, FgRed},
  49. FATAL: {Bold, BgRed},
  50. NONE: {Reset},
  51. }
  52. func (l Level) String() string {
  53. s, ok := toString[l]
  54. if ok {
  55. return s
  56. }
  57. return "info"
  58. }
  59. func (l Level) ColorAttributes() []ColorAttribute {
  60. color, ok := levelToColor[l]
  61. if ok {
  62. return color
  63. }
  64. none := levelToColor[NONE]
  65. return none
  66. }
  67. // MarshalJSON takes a Level and turns it into text
  68. func (l Level) MarshalJSON() ([]byte, error) {
  69. buffer := bytes.NewBufferString(`"`)
  70. buffer.WriteString(toString[l])
  71. buffer.WriteString(`"`)
  72. return buffer.Bytes(), nil
  73. }
  74. // UnmarshalJSON takes text and turns it into a Level
  75. func (l *Level) UnmarshalJSON(b []byte) error {
  76. var tmp any
  77. err := json.Unmarshal(b, &tmp)
  78. if err != nil {
  79. return err
  80. }
  81. switch v := tmp.(type) {
  82. case string:
  83. *l = LevelFromString(v)
  84. case int:
  85. *l = LevelFromString(Level(v).String())
  86. default:
  87. *l = INFO
  88. }
  89. return nil
  90. }
  91. // LevelFromString takes a level string and returns a Level
  92. func LevelFromString(level string) Level {
  93. if l, ok := toLevel[strings.ToLower(level)]; ok {
  94. return l
  95. }
  96. return INFO
  97. }