add log formatting system
Gitea/etcdmtr/pipeline/head This commit looks good Details

This commit is contained in:
dave 2024-02-27 19:15:18 -08:00
parent 9db5748bca
commit bb0a19270e
1 changed files with 58 additions and 8 deletions

View File

@ -3,6 +3,7 @@ package etcdmtr
import (
"fmt"
"os"
"strings"
)
type LogLevel int64
@ -21,13 +22,67 @@ type ELog struct {
name string
Level LogLevel
DefaultLevel LogLevel
Format *LogFormat
}
type LogFormatToken int64
const (
LOGFORMAT_TIMESTAMP LogFormatToken = iota
LOGFORMAT_NAME
LOGFORMAT_MESSAGE
)
type LogFormat struct {
Next *LogFormat
Token LogFormatToken
}
func NewFormat(firstToken LogFormatToken) *LogFormat {
return &LogFormat{
Token: firstToken,
}
}
// Append appends the token/node to the end of the chain, and returns the node Append was called on.
func (f *LogFormat) Append(token LogFormatToken) *LogFormat {
tail := f
for tail.Next != nil {
tail = tail.Next
}
tail.Next = &LogFormat{
Token: token,
}
return f
}
func NewRootLogger() *ELog {
logger := &ELog{
Format: NewFormat(LOGFORMAT_TIMESTAMP).Append(LOGFORMAT_NAME).Append(LOGFORMAT_MESSAGE),
}
return logger
}
func (e *ELog) _Log(level LogLevel, message string, a ...any) (n int, err error) {
if level >= e.Level {
return fmt.Printf(message+"\n", a...)
if level < e.Level {
return 0, nil
}
return 0, nil
log := strings.Builder{}
tail := e.Format
for tail != nil {
switch token := tail.Token; token {
case LOGFORMAT_TIMESTAMP:
log.WriteString("TS")
case LOGFORMAT_NAME:
log.WriteString("main")
case LOGFORMAT_MESSAGE:
log.WriteString(fmt.Sprintf(message, a...))
default:
panic(fmt.Sprintf("bad log format token: %s", token))
}
tail = tail.Next
}
return fmt.Println(log.String())
}
func (e *ELog) Log(message string, a ...any) (n int, err error) {
@ -59,8 +114,3 @@ func (e *ELog) Fatal(message string, a ...any) (n int, err error) {
os.Exit(1)
return 0, nil
}
func NewRootLogger() *ELog {
logger := &ELog{}
return logger
}