gitech

Форк
0
/
level.go 
116 строк · 2.0 Кб
1
// Copyright 2019 The Gitea Authors. All rights reserved.
2
// SPDX-License-Identifier: MIT
3

4
package log
5

6
import (
7
	"bytes"
8
	"strings"
9

10
	"code.gitea.io/gitea/modules/json"
11
)
12

13
// Level is the level of the logger
14
type Level int
15

16
const (
17
	UNDEFINED Level = iota
18
	TRACE
19
	DEBUG
20
	INFO
21
	WARN
22
	ERROR
23
	FATAL
24
	NONE
25
)
26

27
const CRITICAL = ERROR // most logger frameworks doesn't support CRITICAL, and it doesn't seem useful
28

29
var toString = map[Level]string{
30
	UNDEFINED: "undefined",
31

32
	TRACE: "trace",
33
	DEBUG: "debug",
34
	INFO:  "info",
35
	WARN:  "warn",
36
	ERROR: "error",
37

38
	FATAL: "fatal",
39
	NONE:  "none",
40
}
41

42
var toLevel = map[string]Level{
43
	"undefined": UNDEFINED,
44

45
	"trace":   TRACE,
46
	"debug":   DEBUG,
47
	"info":    INFO,
48
	"warn":    WARN,
49
	"warning": WARN,
50
	"error":   ERROR,
51

52
	"fatal": FATAL,
53
	"none":  NONE,
54
}
55

56
var levelToColor = map[Level][]ColorAttribute{
57
	TRACE: {Bold, FgCyan},
58
	DEBUG: {Bold, FgBlue},
59
	INFO:  {Bold, FgGreen},
60
	WARN:  {Bold, FgYellow},
61
	ERROR: {Bold, FgRed},
62
	FATAL: {Bold, BgRed},
63
	NONE:  {Reset},
64
}
65

66
func (l Level) String() string {
67
	s, ok := toString[l]
68
	if ok {
69
		return s
70
	}
71
	return "info"
72
}
73

74
func (l Level) ColorAttributes() []ColorAttribute {
75
	color, ok := levelToColor[l]
76
	if ok {
77
		return color
78
	}
79
	none := levelToColor[NONE]
80
	return none
81
}
82

83
// MarshalJSON takes a Level and turns it into text
84
func (l Level) MarshalJSON() ([]byte, error) {
85
	buffer := bytes.NewBufferString(`"`)
86
	buffer.WriteString(toString[l])
87
	buffer.WriteString(`"`)
88
	return buffer.Bytes(), nil
89
}
90

91
// UnmarshalJSON takes text and turns it into a Level
92
func (l *Level) UnmarshalJSON(b []byte) error {
93
	var tmp any
94
	err := json.Unmarshal(b, &tmp)
95
	if err != nil {
96
		return err
97
	}
98

99
	switch v := tmp.(type) {
100
	case string:
101
		*l = LevelFromString(v)
102
	case int:
103
		*l = LevelFromString(Level(v).String())
104
	default:
105
		*l = INFO
106
	}
107
	return nil
108
}
109

110
// LevelFromString takes a level string and returns a Level
111
func LevelFromString(level string) Level {
112
	if l, ok := toLevel[strings.ToLower(level)]; ok {
113
		return l
114
	}
115
	return INFO
116
}
117

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.