Logging improvements
This commit is contained in:
@@ -14,6 +14,8 @@ var fieldMap = logrus.FieldMap{
|
||||
}
|
||||
|
||||
type Logger interface {
|
||||
WithField(key string, value interface{}) Logger
|
||||
|
||||
Info(...interface{})
|
||||
Error(error, ...interface{})
|
||||
FatalError(error, ...interface{})
|
||||
@@ -40,6 +42,10 @@ type logger struct {
|
||||
logrus.FieldLogger
|
||||
}
|
||||
|
||||
func (l *logger) WithField(key string, value interface{}) Logger {
|
||||
return &logger{l.FieldLogger.WithField(key, value)}
|
||||
}
|
||||
|
||||
func (l *logger) Error(err error, args ...interface{}) {
|
||||
l.FieldLogger.WithError(err).Error(args)
|
||||
}
|
||||
|
||||
@@ -10,16 +10,29 @@ import (
|
||||
"github.com/go-telegram/bot/models"
|
||||
)
|
||||
|
||||
const (
|
||||
chatIDField = "chat_id"
|
||||
usernameField = "username"
|
||||
)
|
||||
|
||||
func NewLoggingMiddleware(logger jsonlog.Logger) bot.Middleware {
|
||||
return func(next bot.HandlerFunc) bot.HandlerFunc {
|
||||
return func(ctx context.Context, bot *bot.Bot, update *models.Update) {
|
||||
if update.Message != nil {
|
||||
text := update.Message.Text
|
||||
if len(update.Message.Caption) > 0 {
|
||||
text = update.Message.Caption
|
||||
}
|
||||
logger.Info(fmt.Sprintf("message from %s: %s", update.Message.From.Username, text))
|
||||
if update.Message == nil {
|
||||
return
|
||||
}
|
||||
|
||||
chatLogger := logger.
|
||||
WithField(chatIDField, update.Message.Chat.ID).
|
||||
WithField(usernameField, update.Message.From.Username)
|
||||
|
||||
text := update.Message.Text
|
||||
if len(update.Message.Caption) > 0 {
|
||||
text = update.Message.Caption
|
||||
}
|
||||
|
||||
chatLogger.Info(fmt.Sprintf("new message: %s", text))
|
||||
|
||||
next(ctx, bot, update)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user