Files
Atay-Makhzan/modules/log/level.go
T

117 lines
2.0 KiB
Go
Raw Normal View History

2019-04-02 08:48:31 +01:00
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2019-04-02 08:48:31 +01:00
package log
import (
"bytes"
"strings"
"code.gitea.io/gitea/modules/json"
2019-04-02 08:48:31 +01:00
)
// Level is the level of the logger
type Level int
const (
2023-05-22 06:35:11 +08:00
UNDEFINED Level = iota
TRACE
2019-04-02 08:48:31 +01:00
DEBUG
INFO
WARN
ERROR
FATAL
NONE
)
2023-05-22 06:35:11 +08:00
const CRITICAL = ERROR // most logger frameworks doesn't support CRITICAL, and it doesn't seem useful
2019-04-02 08:48:31 +01:00
var toString = map[Level]string{
2023-05-22 06:35:11 +08:00
UNDEFINED: "undefined",
TRACE: "trace",
DEBUG: "debug",
INFO: "info",
WARN: "warn",
ERROR: "error",
FATAL: "fatal",
NONE: "none",
2019-04-02 08:48:31 +01:00
}
var toLevel = map[string]Level{
2023-05-22 06:35:11 +08:00
"undefined": UNDEFINED,
"trace": TRACE,
"debug": DEBUG,
"info": INFO,
"warn": WARN,
"warning": WARN,
"error": ERROR,
"fatal": FATAL,
"none": NONE,
2019-04-02 08:48:31 +01:00
}
2023-05-22 06:35:11 +08:00
var levelToColor = map[Level][]ColorAttribute{
TRACE: {Bold, FgCyan},
DEBUG: {Bold, FgBlue},
INFO: {Bold, FgGreen},
WARN: {Bold, FgYellow},
ERROR: {Bold, FgRed},
FATAL: {Bold, BgRed},
NONE: {Reset},
2019-04-02 08:48:31 +01:00
}
func (l Level) String() string {
s, ok := toString[l]
if ok {
return s
}
return "info"
}
2023-05-22 06:35:11 +08:00
func (l Level) ColorAttributes() []ColorAttribute {
2020-10-31 05:36:46 +00:00
color, ok := levelToColor[l]
if ok {
2023-05-22 06:35:11 +08:00
return color
2020-10-31 05:36:46 +00:00
}
none := levelToColor[NONE]
2023-05-22 06:35:11 +08:00
return none
2020-10-31 05:36:46 +00:00
}
2019-04-02 08:48:31 +01:00
// MarshalJSON takes a Level and turns it into text
func (l Level) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(toString[l])
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
// UnmarshalJSON takes text and turns it into a Level
func (l *Level) UnmarshalJSON(b []byte) error {
2023-05-22 06:35:11 +08:00
var tmp any
2019-04-02 08:48:31 +01:00
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
switch v := tmp.(type) {
case string:
2023-05-22 06:35:11 +08:00
*l = LevelFromString(v)
2019-04-02 08:48:31 +01:00
case int:
2023-05-22 06:35:11 +08:00
*l = LevelFromString(Level(v).String())
2019-04-02 08:48:31 +01:00
default:
*l = INFO
}
return nil
}
2023-05-22 06:35:11 +08:00
// LevelFromString takes a level string and returns a Level
func LevelFromString(level string) Level {
if l, ok := toLevel[strings.ToLower(level)]; ok {
return l
}
return INFO
}