-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
97 lines (80 loc) · 2.43 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package tgf
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
// Logger - logger interface that tgf expects from the user.
type Logger interface {
Info(string, ...any)
Error(string, ...any)
Warn(string, ...any)
Debug(string, ...any)
LogUpdate(tgbotapi.Update)
}
// DefaultLogger - This is a basic logger that tgf comes with in case you do not want to wrap your own logger.
type DefaultLogger struct {
infoLogger *log.Logger
warningLogger *log.Logger
debugLogger *log.Logger
errorLogger *log.Logger
update tgbotapi.Update
debug bool
}
// NewDefaultLogger - returns an instance of the default built in logger.
func NewDefaultLogger(debug bool) *DefaultLogger {
flags := log.Ldate | log.Ltime | log.LstdFlags
infoLogger := log.New(os.Stdout, "", flags)
warningLogger := log.New(os.Stdout, "", flags)
debugLogger := log.New(os.Stdout, "", flags)
errorLogger := log.New(os.Stderr, "", flags)
return &DefaultLogger{
infoLogger: infoLogger,
warningLogger: warningLogger,
debugLogger: debugLogger,
errorLogger: errorLogger,
debug: debug,
}
}
func (l *DefaultLogger) getFileName() string {
_, file, line, _ := runtime.Caller(2)
fileName := filepath.Base(file)
return fmt.Sprintf("[%s:%d]\t", fileName, line)
}
func (l *DefaultLogger) Info(format string, v ...any) {
prefix := l.getFileName()
l.infoLogger.Printf(prefix+"[INFO]:\t\t"+format, v...)
}
func (l *DefaultLogger) Error(format string, v ...any) {
prefix := l.getFileName()
l.errorLogger.Printf(prefix+"[ERROR]:\t"+format, v...)
}
func (l *DefaultLogger) Warn(format string, v ...any) {
prefix := l.getFileName()
l.warningLogger.Printf(prefix+"[WARN]:\t"+format, v...)
}
func (l *DefaultLogger) Debug(format string, v ...any) {
if !l.debug {
return
}
prefix := l.getFileName()
l.debugLogger.Printf(prefix+"[DEBUG]:\t"+format, v...)
}
func (l *DefaultLogger) LogUpdate(u tgbotapi.Update) {
prefix := l.getFileName()
message := u.Message
if message == nil {
message = u.CallbackQuery.Message
}
updateID := u.UpdateID
chatID := message.Chat.ID
userID := message.From.ID
messageJSON, _ := json.Marshal(u.Message)
callbackQueryJSON, _ := json.Marshal(u.CallbackQuery)
l.infoLogger.Printf(prefix+"[UPDATE]:\tupdateID: %d, chatID: %d, userID: %d, messageJSON: %s, callbackQueryJSON: %s",
updateID, chatID, userID, messageJSON, callbackQueryJSON)
}