143 lines
2.3 KiB
Go
143 lines
2.3 KiB
Go
package beaver
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.jolheiser.com/beaver/color"
|
|
)
|
|
|
|
var bold = color.New(color.Bold)
|
|
|
|
// Level defines a Beaver logging level
|
|
type Level int
|
|
|
|
const (
|
|
TRACE Level = iota
|
|
DEBUG
|
|
INFO
|
|
WARN
|
|
ERROR
|
|
FATAL
|
|
)
|
|
|
|
// String returns a human-friendly string
|
|
func (l Level) String() string {
|
|
switch l {
|
|
case TRACE:
|
|
return "Trace"
|
|
case DEBUG:
|
|
return "Debug"
|
|
case INFO:
|
|
return "Info"
|
|
case WARN:
|
|
return "Warn"
|
|
case ERROR:
|
|
return "Error"
|
|
case FATAL:
|
|
return "Fatal"
|
|
default:
|
|
return "N/A"
|
|
}
|
|
}
|
|
|
|
// Prefix returns a prefix for a logging level, optionally colored
|
|
func (l Level) Prefix() string {
|
|
var letter string
|
|
switch l {
|
|
case TRACE:
|
|
letter = "T"
|
|
case DEBUG:
|
|
letter = "D"
|
|
case INFO:
|
|
letter = "I"
|
|
case WARN:
|
|
letter = "W"
|
|
case ERROR:
|
|
letter = "E"
|
|
case FATAL:
|
|
letter = "F"
|
|
}
|
|
return fmt.Sprintf("[%s]", letter)
|
|
}
|
|
|
|
// Color returns a Level's color, defaulting to bold
|
|
func (l Level) Color() color.Color {
|
|
switch l {
|
|
case TRACE:
|
|
return color.Trace
|
|
case DEBUG:
|
|
return color.Debug
|
|
case INFO:
|
|
return color.Info
|
|
case WARN:
|
|
return color.Warn
|
|
case ERROR:
|
|
return color.Error
|
|
case FATAL:
|
|
return color.Fatal
|
|
default:
|
|
return bold
|
|
}
|
|
}
|
|
|
|
// Levels returns a list of Beaver logging levels
|
|
func Levels() []Level {
|
|
return []Level{TRACE, DEBUG, INFO, WARN, ERROR, FATAL}
|
|
}
|
|
|
|
// ParseLevel parses a string and returns a Beaver Level, defaulting to Info
|
|
func ParseLevel(level string) Level {
|
|
switch strings.ToUpper(level) {
|
|
case "T", "TRACE":
|
|
return TRACE
|
|
case "D", "DEBUG":
|
|
return DEBUG
|
|
case "I", "INFO":
|
|
return INFO
|
|
case "W", "WARN":
|
|
return WARN
|
|
case "E", "ERROR":
|
|
return ERROR
|
|
case "F", "FATAL":
|
|
return FATAL
|
|
}
|
|
return INFO
|
|
}
|
|
|
|
func timePrefix(t time.Time) string {
|
|
var buf = &[]byte{}
|
|
year, month, day := t.Date()
|
|
itoa(buf, int(month), 2)
|
|
*buf = append(*buf, '/')
|
|
itoa(buf, day, 2)
|
|
*buf = append(*buf, '/')
|
|
itoa(buf, year, 4)
|
|
*buf = append(*buf, ' ')
|
|
|
|
hour, min, sec := t.Clock()
|
|
itoa(buf, hour, 2)
|
|
*buf = append(*buf, ':')
|
|
itoa(buf, min, 2)
|
|
*buf = append(*buf, ':')
|
|
itoa(buf, sec, 2)
|
|
|
|
return string(*buf)
|
|
}
|
|
|
|
func itoa(buf *[]byte, i int, wid int) {
|
|
var b [20]byte
|
|
bp := len(b) - 1
|
|
for i >= 10 || wid > 1 {
|
|
wid--
|
|
q := i / 10
|
|
b[bp] = byte('0' + i - q*10)
|
|
bp--
|
|
i = q
|
|
}
|
|
// i < 10
|
|
b[bp] = byte('0' + i)
|
|
*buf = append(*buf, b[bp:]...)
|
|
}
|