Untitled
unknown
plain_text
a month ago
1.5 kB
1
Indexable
Never
func (mod *Core) Logger() tele.MiddlewareFunc { logger := initializeLogger() return func(next tele.HandlerFunc) tele.HandlerFunc { return func(c tele.Context) error { if update, ok := monitor.NewUpdate(c); ok { updateMap, err := convertStructToMap(update) if err != nil { logger.Error("Failed to decode struct to map", slog.String("error", err.Error())) } else { fields := mapToLogAttributes(updateMap) logger.Info("Update", slog.Group("update", fields)) } } return next(c) } } } func initializeLogger() *slog.Logger { return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ AddSource: true, Level: slog.LevelDebug, })) } func convertStructToMap(input interface{}) (map[string]interface{}, error) { result := make(map[string]interface{}) err := mapstructure.Decode(input, &result) return result, err } func mapToLogAttributes(updateMap map[string]interface{}) (fields []slog.Attr) { for k, v := range updateMap { switch val := v.(type) { case string: fields = append(fields, slog.String(k, val)) case bool: fields = append(fields, slog.Bool(k, val)) case int: fields = append(fields, slog.Int(k, val)) case int64: fields = append(fields, slog.Int64(k, val)) case uint: fields = append(fields, slog.Uint64(k, uint64(val))) case uint64: fields = append(fields, slog.Uint64(k, val)) default: fields = append(fields, slog.Any(k, val)) } } return fields }
Leave a Comment