add appender

This commit is contained in:
程广 2023-01-23 11:35:44 +08:00
parent db847840ff
commit 2bbe9dcf05
2 changed files with 74 additions and 14 deletions

37
console.go Normal file
View File

@ -0,0 +1,37 @@
package gologger
import "fmt"
const (
ErrorTemplate = "\033[1;31;40m%s\033[0m\n"
WarnTemplate = "\033[1;33;40m%s\033[0m\n"
InfoTemplate = "\033[1;32;40m%s\033[0m\n"
DebugTemplate = "\033[1;34;40m%s\033[0m\n"
TraceTemplate = "\033[1;35;40m%s\033[0m\n"
)
type ConsoleAppender struct{}
func (c *ConsoleAppender) GetName() string {
return "console"
}
func (c *ConsoleAppender) Append(logEvent LogEvent) {
data := []interface{}{
logEvent.Ts.Format("2006-01-02 15:04:05"),
}
data = append(data, logEvent.Data...)
logMsg := fmt.Sprint(data...)
switch logEvent.Level {
case Error:
fmt.Printf(ErrorTemplate, logMsg)
case Warn:
fmt.Printf(WarnTemplate, logMsg)
case Info:
fmt.Printf(InfoTemplate, logMsg)
case Debug:
fmt.Printf(DebugTemplate, logMsg)
case Trace:
fmt.Printf(TraceTemplate, logMsg)
}
}

51
main.go
View File

@ -1,7 +1,6 @@
package gologger
import (
"fmt"
"time"
)
@ -17,46 +16,70 @@ const (
var loggerMap map[string]Logger = map[string]Logger{}
type LogConfig struct {
Name string
Level int
Name string
Level int
Appender LoggerAppender
}
type Logger struct {
LogConfig
}
func (l *Logger) log(Level int, msg string) {
now := time.Now()
type LogEvent struct {
Ts time.Time
Level int
Data []interface{}
}
type LoggerAppender interface {
GetName() string
Append(logEvent LogEvent)
}
var consoleAppender LoggerAppender = &ConsoleAppender{}
var defaultLogger = &LogConfig{
Level: Error,
Appender: consoleAppender,
}
func (l *Logger) log(Level int, msg ...interface{}) {
if Level <= l.Level {
fmt.Println(now.Format("2006-01-02 15:04:05"), " ", l.Name, ": ", msg)
now := time.Now()
logEvent := LogEvent{now, Level, msg}
l.Appender.Append(logEvent)
// fmt.Println(now.Format("2006-01-02 15:04:05"), " ", l.Name, ": ", msg)
}
}
func (l *Logger) Error(msg string) {
func (l *Logger) Error(msg ...interface{}) {
l.log(Error, msg)
}
func (l *Logger) Warn(msg string) {
func (l *Logger) Warn(msg ...interface{}) {
l.log(Warn, msg)
}
func (l *Logger) Info(msg string) {
func (l *Logger) Info(msg ...interface{}) {
l.log(Info, msg)
}
func (l *Logger) Debug(msg string) {
func (l *Logger) Debug(msg ...interface{}) {
l.log(Debug, msg)
}
func (l *Logger) Trace(msg string) {
func (l *Logger) Trace(msg ...interface{}) {
l.log(Trace, msg)
}
func GetLogger(logConfig LogConfig) Logger {
if logger, ok := loggerMap[logConfig.Name]; ok {
return logger
} else {
logger = Logger{logConfig}
loggerMap[logConfig.Name] = logger
return logger
logger := &Logger{logConfig}
if logger.Appender == nil {
logger.Appender = defaultLogger.Appender
}
loggerMap[logConfig.Name] = *logger
return *logger
}
}