diff --git a/console.go b/console.go new file mode 100644 index 0000000..2ca83a4 --- /dev/null +++ b/console.go @@ -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) + } +} diff --git a/main.go b/main.go index b276557..b63fbe9 100644 --- a/main.go +++ b/main.go @@ -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 } }