Files
TrollSSH/internal/logx/logx.go
T

90 lines
1.8 KiB
Go
Raw Normal View History

2026-07-16 23:29:14 +07:00
package logx
2026-07-13 17:47:00 +07:00
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
)
2026-07-16 23:29:14 +07:00
type Level int
2026-07-13 17:47:00 +07:00
const (
2026-07-16 23:29:14 +07:00
LevelDebug Level = 10
LevelInfo Level = 20
LevelWarn Level = 30
LevelError Level = 40
2026-07-13 17:47:00 +07:00
)
2026-07-16 23:29:14 +07:00
var threshold = ResolveThreshold()
2026-07-13 17:47:00 +07:00
2026-07-16 23:29:14 +07:00
func ResolveThreshold() Level {
2026-07-13 17:47:00 +07:00
switch strings.ToLower(strings.TrimSpace(os.Getenv("LOG_LEVEL"))) {
case "debug":
2026-07-16 23:29:14 +07:00
return LevelDebug
2026-07-13 17:47:00 +07:00
case "warn":
2026-07-16 23:29:14 +07:00
return LevelWarn
2026-07-13 17:47:00 +07:00
case "error":
2026-07-16 23:29:14 +07:00
return LevelError
2026-07-13 17:47:00 +07:00
default:
2026-07-16 23:29:14 +07:00
return LevelInfo
2026-07-13 17:47:00 +07:00
}
}
2026-07-16 23:29:14 +07:00
func SetThreshold(level Level) { threshold = level }
func Sanitize(value any) string {
return SanitizeN(value, 200)
2026-07-13 17:47:00 +07:00
}
2026-07-16 23:29:14 +07:00
func SanitizeN(value any, maxLength int) string {
2026-07-13 17:47:00 +07:00
var str string
switch v := value.(type) {
case nil:
str = ""
case string:
str = v
default:
str = fmt.Sprint(v)
}
var b strings.Builder
count := 0
2026-07-13 17:47:00 +07:00
for _, r := range str {
if count >= maxLength {
b.WriteRune('…')
return b.String()
}
2026-07-13 17:47:00 +07:00
if r < 0x20 || (r >= 0x7f && r <= 0x9f) {
b.WriteRune('')
} else {
b.WriteRune(r)
}
count++
2026-07-13 17:47:00 +07:00
}
return b.String()
2026-07-13 17:47:00 +07:00
}
2026-07-16 23:29:14 +07:00
func emit(level Level, name string, stream *os.File, args []any) {
if level < threshold {
2026-07-13 17:47:00 +07:00
return
}
parts := make([]string, len(args))
for i, a := range args {
if s, ok := a.(string); ok {
parts[i] = s
} else if b, err := json.Marshal(a); err == nil {
parts[i] = string(b)
} else {
parts[i] = fmt.Sprint(a)
}
}
ts := time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
_, _ = fmt.Fprintf(stream, "[%s] %-5s %s\n", ts, strings.ToUpper(name), strings.Join(parts, " "))
2026-07-13 17:47:00 +07:00
}
2026-07-16 23:29:14 +07:00
func Debug(args ...any) { emit(LevelDebug, "debug", os.Stdout, args) }
func Info(args ...any) { emit(LevelInfo, "info", os.Stdout, args) }
func Warn(args ...any) { emit(LevelWarn, "warn", os.Stderr, args) }
func Error(args ...any) { emit(LevelError, "error", os.Stderr, args) }