package log import ( "fmt" "git.nobla.cn/golang/kos/util/env" "strconv" "time" ) const ( FG_BLACK int = 30 FG_RED = 31 FG_GREEN = 32 FG_YELLOW = 33 FG_BLUE = 34 FG_PURPLE = 35 FG_CYAN = 36 FG_GREY = 37 ) var ( levelColor = map[int]int{ TraceLevel: FG_GREY, DebugLevel: FG_BLUE, InfoLevel: FG_GREEN, WarnLevel: FG_PURPLE, ErrorLevel: FG_RED, FatalLevel: FG_RED, PanicLevel: FG_RED, } ) type Console struct { Level int DisableColor bool DisableTime bool prefix string } func (log *Console) SetLevel(lv int) { log.Level = lv } func (log *Console) Prefix(s string) { log.prefix = s } func (log *Console) Print(i ...interface{}) { log.write(TraceLevel, fmt.Sprint(i...)) } func (log *Console) Printf(format string, args ...interface{}) { log.write(TraceLevel, fmt.Sprintf(format, args...)) } func (log *Console) Debug(i ...interface{}) { log.write(DebugLevel, fmt.Sprint(i...)) } func (log *Console) Debugf(format string, args ...interface{}) { log.write(DebugLevel, fmt.Sprintf(format, args...)) } func (log *Console) Info(i ...interface{}) { log.write(InfoLevel, fmt.Sprint(i...)) } func (log *Console) Infof(format string, args ...interface{}) { log.write(InfoLevel, fmt.Sprintf(format, args...)) } func (log *Console) Warn(i ...interface{}) { log.write(WarnLevel, fmt.Sprint(i...)) } func (log *Console) Warnf(format string, args ...interface{}) { log.write(WarnLevel, fmt.Sprintf(format, args...)) } func (log *Console) Error(i ...interface{}) { log.write(ErrorLevel, fmt.Sprint(i...)) } func (log *Console) Errorf(format string, args ...interface{}) { log.write(ErrorLevel, fmt.Sprintf(format, args...)) } func (log *Console) Fatal(i ...interface{}) { log.write(FatalLevel, fmt.Sprint(i...)) } func (log *Console) Fatalf(format string, args ...interface{}) { log.write(FatalLevel, fmt.Sprintf(format, args...)) } func (log *Console) Panic(i ...interface{}) { log.write(PanicLevel, fmt.Sprint(i...)) } func (log *Console) Panicf(format string, args ...interface{}) { log.write(PanicLevel, fmt.Sprintf(format, args...)) } func (log *Console) write(level int, s string) { var ls string if log.Level > level { return } if log.DisableColor { ls = getLevelText(level) } else { ls = fmt.Sprintf("\033[0m\033[%dm[%s]\033[0m", levelColor[level], getLevelText(level)) } if log.prefix != "" { ls += " [" + log.prefix + "]" } if log.DisableTime { fmt.Println(ls + " " + s) } else { fmt.Println(time.Now().Format("2006-01-02 15:04:05") + " " + ls + " " + s) } } func NewConsoleLogger() *Console { lg := &Console{} lg.DisableColor, _ = strconv.ParseBool(env.Get("VOX_DISABLE_LOG_COLOR", "false")) lg.DisableTime, _ = strconv.ParseBool(env.Get("VOX_DISABLE_LOG_DATETIME", "false")) return lg }