all repos — disgord @ a4093084b5f92b1e3c91c66c157baba16346c4dc

A simple Discord bot in Go.

src/mylog/log.go (view raw)

  1package mylog
  2
  3import (
  4	"io"
  5	"log"
  6)
  7
  8type Level uint
  9
 10const (
 11	FATAL Level = iota
 12	ERROR
 13	WARN
 14	INFO
 15	DEBUG
 16)
 17
 18type Logger struct {
 19	logger      *log.Logger
 20	fatalLogger *log.Logger
 21	errorLogger *log.Logger
 22	warnLogger  *log.Logger
 23	infoLogger  *log.Logger
 24	debugLogger *log.Logger
 25	level       Level
 26	name        string
 27}
 28
 29func NewLogger(out io.Writer, name string, level Level) (l *Logger) {
 30	l = &Logger{
 31		level: level,
 32
 33		logger:      log.New(out, "", 3),
 34		fatalLogger: log.New(out, "", 3),
 35		errorLogger: log.New(out, "", 3),
 36		warnLogger:  log.New(out, "", 3),
 37		infoLogger:  log.New(out, "", 3),
 38		debugLogger: log.New(out, "", 3),
 39	}
 40
 41	l.SetName(name)
 42	return
 43
 44}
 45
 46func parsePrefix(name string, level string) string {
 47	return level + " " + name + " "
 48}
 49
 50func (l Logger) GetLevel() Level {
 51	return l.level
 52}
 53
 54func (l *Logger) SetLevel(lvl Level) {
 55	l.level = lvl
 56}
 57
 58func (l *Logger) SetName(name string) {
 59	l.name = name
 60	l.logger.SetPrefix(parsePrefix(name, "LOG  "))
 61	l.fatalLogger.SetPrefix(parsePrefix(name, "FATAL"))
 62	l.errorLogger.SetPrefix(parsePrefix(name, "ERROR"))
 63	l.warnLogger.SetPrefix(parsePrefix(name, "WARN "))
 64	l.infoLogger.SetPrefix(parsePrefix(name, "INFO "))
 65	l.debugLogger.SetPrefix(parsePrefix(name, "DEBUG"))
 66}
 67
 68// log functions
 69
 70func (l Logger) Printf(format string, v ...any) {
 71	l.logger.Printf(format, v...)
 72}
 73
 74func (l Logger) Println(v ...any) {
 75	l.logger.Println(v...)
 76}
 77
 78func (l Logger) Fatal(v ...any) {
 79	l.fatalLogger.Fatal(v...)
 80}
 81
 82func (l Logger) Fatalf(format string, v ...any) {
 83	l.fatalLogger.Fatalf(format, v...)
 84}
 85
 86func (l Logger) Error(v ...any) {
 87	if l.level < ERROR {
 88		return
 89	}
 90	l.errorLogger.Println(v...)
 91}
 92
 93func (l Logger) Errorf(format string, v ...any) {
 94	if l.level < ERROR {
 95		return
 96	}
 97	l.errorLogger.Printf(format, v...)
 98}
 99
100func (l Logger) Warn(v ...any) {
101	if l.level < WARN {
102		return
103	}
104	l.warnLogger.Println(v...)
105}
106
107func (l Logger) Warnf(format string, v ...any) {
108	if l.level < WARN {
109		return
110	}
111	l.warnLogger.Printf(format, v...)
112}
113
114func (l Logger) Info(v ...any) {
115	if l.level < INFO {
116		return
117	}
118	l.infoLogger.Println(v...)
119}
120
121func (l Logger) Infof(format string, v ...any) {
122	if l.level < INFO {
123		return
124	}
125	l.infoLogger.Printf(format, v...)
126}
127
128func (l Logger) Debug(v ...any) {
129	if l.level < DEBUG {
130		return
131	}
132	l.debugLogger.Println(v...)
133}
134
135func (l Logger) Debugf(format string, v ...any) {
136	if l.level < DEBUG {
137		return
138	}
139	l.debugLogger.Printf(format, v...)
140}