gologger/main.go

87 lines
1.4 KiB
Go
Raw Normal View History

2023-01-23 10:09:21 +08:00
package gologger
2023-01-23 09:59:30 +08:00
import (
"time"
)
const (
NoLog = iota
Error
Warn
Info
Debug
Trace
)
2023-01-23 10:39:10 +08:00
var loggerMap map[string]Logger = map[string]Logger{}
2023-01-23 10:24:39 +08:00
2023-01-23 10:20:17 +08:00
type LogConfig struct {
2023-01-23 11:35:44 +08:00
Name string
Level int
Appender LoggerAppender
2023-01-23 10:20:17 +08:00
}
2023-01-23 09:59:30 +08:00
type Logger struct {
2023-01-23 10:20:17 +08:00
LogConfig
2023-01-23 09:59:30 +08:00
}
2023-01-23 11:35:44 +08:00
type LogEvent struct {
2023-03-11 21:40:33 +08:00
Ts time.Time
Level int
Data []interface{}
ELogger *Logger
2023-01-23 11:35:44 +08:00
}
type LoggerAppender interface {
GetName() string
Append(logEvent LogEvent)
}
var consoleAppender LoggerAppender = &ConsoleAppender{}
var defaultLogger = &LogConfig{
Level: Error,
Appender: consoleAppender,
}
2023-01-23 11:48:03 +08:00
func (l *Logger) log(Level int, msg []interface{}) {
2023-01-23 11:35:44 +08:00
2023-01-23 10:20:17 +08:00
if Level <= l.Level {
2023-01-23 11:35:44 +08:00
now := time.Now()
2023-03-11 21:40:33 +08:00
logEvent := LogEvent{now, Level, msg, l}
2023-01-23 11:35:44 +08:00
l.Appender.Append(logEvent)
// fmt.Println(now.Format("2006-01-02 15:04:05"), " ", l.Name, ": ", msg)
2023-01-23 09:59:30 +08:00
}
}
2023-01-23 11:35:44 +08:00
func (l *Logger) Error(msg ...interface{}) {
2023-01-23 09:59:30 +08:00
l.log(Error, msg)
}
2023-01-23 11:35:44 +08:00
func (l *Logger) Warn(msg ...interface{}) {
2023-01-23 09:59:30 +08:00
l.log(Warn, msg)
}
2023-01-23 11:35:44 +08:00
func (l *Logger) Info(msg ...interface{}) {
2023-01-23 09:59:30 +08:00
l.log(Info, msg)
}
2023-01-23 11:35:44 +08:00
func (l *Logger) Debug(msg ...interface{}) {
2023-01-23 09:59:30 +08:00
l.log(Debug, msg)
}
2023-01-23 11:35:44 +08:00
func (l *Logger) Trace(msg ...interface{}) {
2023-01-23 09:59:30 +08:00
l.log(Trace, msg)
}
2023-01-23 10:20:17 +08:00
func GetLogger(logConfig LogConfig) Logger {
2023-01-23 10:24:39 +08:00
if logger, ok := loggerMap[logConfig.Name]; ok {
return logger
} else {
2023-01-23 11:35:44 +08:00
logger := &Logger{logConfig}
if logger.Appender == nil {
logger.Appender = defaultLogger.Appender
}
loggerMap[logConfig.Name] = *logger
return *logger
2023-01-23 10:24:39 +08:00
}
2023-01-23 09:59:30 +08:00
}