2020-10-09 21:31:19 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
tele "gopkg.in/tucnak/telebot.v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type LoggerFieldsFunc = func(tele.Context) logrus.Fields
|
|
|
|
|
|
|
|
func Logger(logger *logrus.Logger, fieldsFunc ...LoggerFieldsFunc) tele.MiddlewareFunc {
|
|
|
|
if logger == nil {
|
|
|
|
logger = logrus.New()
|
|
|
|
}
|
|
|
|
|
|
|
|
var f LoggerFieldsFunc
|
|
|
|
if len(fieldsFunc) > 0 && fieldsFunc[0] != nil {
|
|
|
|
f = fieldsFunc[0]
|
|
|
|
} else {
|
|
|
|
f = func(c tele.Context) logrus.Fields { return nil }
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(next tele.HandlerFunc) tele.HandlerFunc {
|
|
|
|
return func(c tele.Context) error {
|
2020-10-12 15:48:29 +00:00
|
|
|
data := c.Data()
|
2020-10-12 18:01:34 +00:00
|
|
|
if clb := c.Callback(); clb != nil {
|
2020-10-20 10:29:07 +00:00
|
|
|
uniq := clb.Unique
|
|
|
|
if data == "" {
|
|
|
|
data = uniq
|
|
|
|
} else {
|
|
|
|
data = uniq + "|" + data
|
|
|
|
}
|
2020-10-12 18:01:34 +00:00
|
|
|
} else if data == "" {
|
2020-10-12 15:48:29 +00:00
|
|
|
data = c.Text()
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.WithFields(f(c)).Info(data)
|
2020-10-09 21:31:19 +00:00
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func DefaultLogger() tele.MiddlewareFunc {
|
|
|
|
return Logger(logrus.New(), func(c tele.Context) logrus.Fields {
|
|
|
|
sender := c.Sender()
|
|
|
|
if sender == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return logrus.Fields{
|
|
|
|
// Default set of fields
|
|
|
|
"sender": sender.Recipient(),
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|