Files

68 lines
1.3 KiB
Go
Raw Permalink Normal View History

package mq
import (
"fmt"
"log"
)
// LogLevel 日志级别
type LogLevel string
const (
LevelInfo LogLevel = "INFO"
LevelError LogLevel = "ERROR"
LevelWarn LogLevel = "WARN"
)
// Logger 简单的结构化日志封装
// 格式: [Component] [Level] Message key1=value1 key2=value2
type Logger struct {
Component string
}
func NewLogger(component string) *Logger {
return &Logger{Component: component}
}
func (l *Logger) Info(msg string, keysAndValues ...interface{}) {
l.log(LevelInfo, msg, keysAndValues...)
}
func (l *Logger) Warn(msg string, keysAndValues ...interface{}) {
l.log(LevelWarn, msg, keysAndValues...)
}
func (l *Logger) Error(msg string, keysAndValues ...interface{}) {
l.log(LevelError, msg, keysAndValues...)
}
func (l *Logger) log(level LogLevel, msg string, args ...interface{}) {
// 构建 key=value 字符串
var kvStr string
for i := 0; i < len(args); i += 2 {
key := args[i]
var val interface{} = ""
if i+1 < len(args) {
val = args[i+1]
}
if kvStr != "" {
kvStr += " "
}
kvStr += logFormatKV(key, val)
}
if kvStr != "" {
log.Printf("[%s] [%s] %s %s", l.Component, level, msg, kvStr)
} else {
log.Printf("[%s] [%s] %s", l.Component, level, msg)
}
}
func logFormatKV(key, val interface{}) string {
return logStr(key) + "=" + logStr(val)
}
func logStr(v interface{}) string {
return fmt.Sprint(v)
}