Илья Глазунов 8f5b9a5cd1 go implementation
2025-12-11 16:52:13 +03:00

137 lines
2.6 KiB
Go

package logging
import (
"fmt"
"os"
"time"
"github.com/konduktor/konduktor/internal/config"
)
type Config struct {
Level string
TimestampFormat string
}
type Logger struct {
level string
timestampFormat string
configFull *config.LoggingConfig
}
func New(cfg Config) (*Logger, error) {
timestampFormat := cfg.TimestampFormat
if timestampFormat == "" {
timestampFormat = "2006-01-02 15:04:05"
}
return &Logger{
level: cfg.Level,
timestampFormat: timestampFormat,
}, nil
}
func NewFromConfig(cfg config.LoggingConfig) (*Logger, error) {
timestampFormat := cfg.Format.TimestampFormat
if timestampFormat == "" {
timestampFormat = "2006-01-02 15:04:05"
}
return &Logger{
level: cfg.Level,
timestampFormat: timestampFormat,
configFull: &cfg,
}, nil
}
func (l *Logger) formatTime() string {
return time.Now().Format(l.timestampFormat)
}
func (l *Logger) log(level string, msg string, fields ...interface{}) {
timestamp := l.formatTime()
// Simple console output for now
// TODO: Implement proper structured logging with zap
output := timestamp + " [" + level + "] " + msg
if len(fields) > 0 {
output += " {"
for i := 0; i < len(fields); i += 2 {
if i > 0 {
output += ", "
}
if i+1 < len(fields) {
output += fields[i].(string) + "=" + formatValue(fields[i+1])
}
}
output += "}"
}
os.Stdout.WriteString(output + "\n")
}
func formatValue(v interface{}) string {
switch val := v.(type) {
case string:
return val
case int:
return fmt.Sprintf("%d", val)
case int64:
return fmt.Sprintf("%d", val)
case float64:
return fmt.Sprintf("%.2f", val)
case bool:
return fmt.Sprintf("%t", val)
case error:
return val.Error()
default:
return fmt.Sprintf("%v", val)
}
}
func (l *Logger) Debug(msg string, fields ...interface{}) {
if l.shouldLog("DEBUG") {
l.log("DEBUG", msg, fields...)
}
}
func (l *Logger) Info(msg string, fields ...interface{}) {
if l.shouldLog("INFO") {
l.log("INFO", msg, fields...)
}
}
func (l *Logger) Warn(msg string, fields ...interface{}) {
if l.shouldLog("WARN") {
l.log("WARN", msg, fields...)
}
}
func (l *Logger) Error(msg string, fields ...interface{}) {
if l.shouldLog("ERROR") {
l.log("ERROR", msg, fields...)
}
}
func (l *Logger) shouldLog(level string) bool {
levels := map[string]int{
"DEBUG": 0,
"INFO": 1,
"WARN": 2,
"ERROR": 3,
}
currentLevel, ok := levels[l.level]
if !ok {
currentLevel = 1 // Default to INFO
}
msgLevel, ok := levels[level]
if !ok {
msgLevel = 1
}
return msgLevel >= currentLevel
}