Skip to content

Commit

Permalink
feat: Support slog
Browse files Browse the repository at this point in the history
  • Loading branch information
raed-shomali authored and arusso committed Nov 24, 2023
1 parent b575f08 commit da0619f
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 85 deletions.
11 changes: 5 additions & 6 deletions examples/interaction-middleware/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,11 @@ func slackerInteractive(ctx *slacker.InteractionContext) {
func LoggingInteractionMiddleware() slacker.InteractionMiddlewareHandler {
return func(next slacker.InteractionHandler) slacker.InteractionHandler {
return func(ctx *slacker.InteractionContext) {
ctx.Logger().Infof(
"%s initiated \"%s\" with action \"%v\" in channel %s\n",
ctx.Callback().User.ID,
ctx.Definition().InteractionID,
ctx.Callback().ActionCallback.BlockActions[0].ActionID,
ctx.Callback().Channel.ID,
ctx.Logger().Info("logging interaction middleware",
"user_id", ctx.Callback().User.ID,
"interaction_id", ctx.Definition().InteractionID,
"action_id", ctx.Callback().ActionCallback.BlockActions[0].ActionID,
"channel_id", ctx.Callback().Channel.ID,
)
next(ctx)
}
Expand Down
12 changes: 6 additions & 6 deletions examples/job-middleware/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ func main() {
func LoggingJobMiddleware() slacker.JobMiddlewareHandler {
return func(next slacker.JobHandler) slacker.JobHandler {
return func(ctx *slacker.JobContext) {
ctx.Logger().Infof(
"%s started\n",
ctx.Definition().Name,
ctx.Logger().Info(
"job middleware before",
"job_name", ctx.Definition().Name,
)
next(ctx)
ctx.Logger().Infof(
"%s ended\n",
ctx.Definition().Name,
ctx.Logger().Info(
"job middleware after",
"job_name", ctx.Definition().Name,
)
}
}
Expand Down
34 changes: 11 additions & 23 deletions examples/logger/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"log"
"log/slog"
"os"

"github.com/shomali11/slacker/v2"
Expand Down Expand Up @@ -35,40 +36,27 @@ func main() {
}

type MyLogger struct {
debugMode bool
logger *log.Logger
logger *slog.Logger
}

func newLogger() *MyLogger {
return &MyLogger{
logger: log.New(os.Stdout, "something ", log.LstdFlags|log.Lshortfile|log.Lmsgprefix),
logger: slog.New(slog.NewTextHandler(os.Stdout, nil)),
}
}

func (l *MyLogger) Info(args ...interface{}) {
l.logger.Println(args...)
func (l *MyLogger) Info(msg string, args ...any) {
l.logger.Info(msg, args...)
}

func (l *MyLogger) Infof(format string, args ...interface{}) {
l.logger.Printf(format, args...)
func (l *MyLogger) Debug(msg string, args ...any) {
l.logger.Debug(msg, args...)
}

func (l *MyLogger) Debug(args ...interface{}) {
if l.debugMode {
l.logger.Println(args...)
}
}

func (l *MyLogger) Debugf(format string, args ...interface{}) {
if l.debugMode {
l.logger.Printf(format, args...)
}
}

func (l *MyLogger) Error(args ...interface{}) {
l.logger.Println(args...)
func (l *MyLogger) Warn(msg string, args ...any) {
l.logger.Warn(msg, args...)
}

func (l *MyLogger) Errorf(format string, args ...interface{}) {
l.logger.Printf(format, args...)
func (l *MyLogger) Error(msg string, args ...any) {
l.logger.Error(msg, args...)
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/shomali11/slacker/v2

go 1.18
go 1.21

require (
github.com/robfig/cron/v3 v3.0.1
Expand Down
51 changes: 24 additions & 27 deletions logger.go
Original file line number Diff line number Diff line change
@@ -1,55 +1,52 @@
package slacker

import (
"log"
"log/slog"
"os"
)

type Logger interface {
Info(args ...interface{})
Infof(format string, args ...interface{})
Debug(args ...interface{})
Debugf(format string, args ...interface{})
Error(args ...interface{})
Errorf(format string, args ...interface{})
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}

type builtinLogger struct {
debugMode bool
logger *log.Logger
logger *slog.Logger
}

func newBuiltinLogger(debugMode bool) *builtinLogger {
opts := &slog.HandlerOptions{
Level: getLogLevel(debugMode),
}

return &builtinLogger{
debugMode: debugMode,
logger: log.New(os.Stdout, "", log.LstdFlags),
logger: slog.New(slog.NewJSONHandler(os.Stdout, opts)),
}
}

func (l *builtinLogger) Info(args ...interface{}) {
l.logger.Println(args...)
func (l *builtinLogger) Info(msg string, args ...any) {
l.logger.Info(msg, args...)
}

func (l *builtinLogger) Infof(format string, args ...interface{}) {
l.logger.Printf(format, args...)
func (l *builtinLogger) Debug(msg string, args ...any) {
l.logger.Debug(msg, args...)
}

func (l *builtinLogger) Debug(args ...interface{}) {
if l.debugMode {
l.logger.Println(args...)
}
func (l *builtinLogger) Warn(msg string, args ...any) {
l.logger.Warn(msg, args...)
}

func (l *builtinLogger) Debugf(format string, args ...interface{}) {
if l.debugMode {
l.logger.Printf(format, args...)
}
func (l *builtinLogger) Error(msg string, args ...any) {
l.logger.Error(msg, args...)
}

func (l *builtinLogger) Error(args ...interface{}) {
l.logger.Println(args...)
}

func (l *builtinLogger) Errorf(format string, args ...interface{}) {
l.logger.Printf(format, args...)
func getLogLevel(isDebugMode bool) slog.Level {
if isDebugMode {
return slog.LevelDebug
}
return slog.LevelInfo
}
4 changes: 2 additions & 2 deletions message_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func getChannel(logger Logger, slackClient *slack.Client, channelID string) *sla
IncludeLocale: false,
IncludeNumMembers: false})
if err != nil {
logger.Errorf("unable to get channel info for %s: %v\n", channelID, err)
logger.Error("unable to get channel info", "channel_id", channelID, "error", err)
return nil
}
return channel
Expand All @@ -131,7 +131,7 @@ func getUserProfile(logger Logger, slackClient *slack.Client, userID string) *sl

user, err := slackClient.GetUserInfo(userID)
if err != nil {
logger.Errorf("unable to get user info for %s: %v\n", userID, err)
logger.Error("unable to get user info", "user_id", userID, "error", err)
return nil
}
return &user.Profile
Expand Down
4 changes: 2 additions & 2 deletions response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (r *Writer) Delete(channel string, messageTimestamp string) (string, error)
messageTimestamp,
)
if err != nil {
r.logger.Errorf("failed to delete message: %v\n", err)
r.logger.Error("failed to delete message", "error", err)
}
return timestamp, err
}
Expand Down Expand Up @@ -83,7 +83,7 @@ func (r *Writer) post(channel string, message string, blocks []slack.Block, opti
opts...,
)
if err != nil {
r.logger.Errorf("failed to post message: %v\n", err)
r.logger.Error("failed to post message", "error", err)
}
return timestamp, err
}
36 changes: 18 additions & 18 deletions slacker.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func (s *Slacker) AddCommandGroup(prefix string) *CommandGroup {
// AddInteraction define a new interaction and append it to the list of interactions
func (s *Slacker) AddInteraction(definition *InteractionDefinition) {
if len(definition.InteractionID) == 0 {
s.logger.Error("missing `ID`")
s.logger.Error("missing `InteractionID`")
return
}
if len(definition.Type) == 0 {
Expand Down Expand Up @@ -223,23 +223,23 @@ func (s *Slacker) Listen(ctx context.Context) error {

switch socketEvent.Type {
case socketmode.EventTypeConnecting:
s.logger.Infof("connecting to Slack with Socket Mode...\n")
s.logger.Info("connecting to Slack with Socket Mode...")

if s.onConnecting == nil {
continue
}
go s.onConnecting(socketEvent)

case socketmode.EventTypeConnectionError:
s.logger.Infof("connection failed. Retrying later...\n")
s.logger.Info("connection failed. Retrying later...")

if s.onConnectionError == nil {
continue
}
go s.onConnectionError(socketEvent)

case socketmode.EventTypeConnected:
s.logger.Infof("connected to Slack with Socket Mode.\n")
s.logger.Info("connected to Slack with Socket Mode")

if s.onConnected == nil {
continue
Expand All @@ -248,15 +248,15 @@ func (s *Slacker) Listen(ctx context.Context) error {

case socketmode.EventTypeHello:
s.appID = socketEvent.Request.ConnectionInfo.AppID
s.logger.Infof("connected as App ID %v\n", s.appID)
s.logger.Info("connected", "app_id", s.appID)

if s.onHello == nil {
continue
}
go s.onHello(socketEvent)

case socketmode.EventTypeDisconnect:
s.logger.Infof("disconnected due to %v\n", socketEvent.Request.Reason)
s.logger.Info("disconnected", "reason", socketEvent.Request.Reason)

if s.onDisconnected == nil {
continue
Expand All @@ -266,7 +266,7 @@ func (s *Slacker) Listen(ctx context.Context) error {
case socketmode.EventTypeEventsAPI:
event, ok := socketEvent.Data.(slackevents.EventsAPIEvent)
if !ok {
s.logger.Debugf("ignored %+v\n", socketEvent)
s.logger.Debug("ignored event", "event", socketEvent)
continue
}

Expand All @@ -277,7 +277,7 @@ func (s *Slacker) Listen(ctx context.Context) error {
if s.unsupportedEventHandler != nil {
s.unsupportedEventHandler(socketEvent)
} else {
s.logger.Debugf("unsupported event received %+v\n", socketEvent)
s.logger.Debug("unsupported event", "event", socketEvent)
}
continue
}
Expand All @@ -290,14 +290,14 @@ func (s *Slacker) Listen(ctx context.Context) error {
if s.unsupportedEventHandler != nil {
s.unsupportedEventHandler(socketEvent)
} else {
s.logger.Debugf("unsupported event received %+v\n", socketEvent)
s.logger.Debug("unsupported event", "event", socketEvent)
}
}

case socketmode.EventTypeSlashCommand:
event, ok := socketEvent.Data.(slack.SlashCommand)
if !ok {
s.logger.Debugf("ignored %+v\n", socketEvent)
s.logger.Debug("ignored event", "event", socketEvent)
continue
}

Expand All @@ -309,7 +309,7 @@ func (s *Slacker) Listen(ctx context.Context) error {
case socketmode.EventTypeInteractive:
callback, ok := socketEvent.Data.(slack.InteractionCallback)
if !ok {
s.logger.Debugf("ignored %+v\n", socketEvent)
s.logger.Debug("ignored event", "event", socketEvent)
continue
}

Expand All @@ -322,7 +322,7 @@ func (s *Slacker) Listen(ctx context.Context) error {
if s.unsupportedEventHandler != nil {
s.unsupportedEventHandler(socketEvent)
} else {
s.logger.Debugf("unsupported event received %+v\n", socketEvent)
s.logger.Debug("unsupported event.", "event", socketEvent)
}
}
}
Expand Down Expand Up @@ -432,7 +432,7 @@ func (s *Slacker) startCronJobs(ctx context.Context) {
jobCtx := newJobContext(ctx, s.logger, s.slackClient, definition)
_, err := s.cronClient.AddFunc(definition.CronExpression, executeJob(jobCtx, definition.Handler, middlewares...))
if err != nil {
s.logger.Errorf(err.Error())
s.logger.Error(err.Error())
}

}
Expand Down Expand Up @@ -486,7 +486,7 @@ func (s *Slacker) handleInteractionEvent(ctx context.Context, callback *slack.In
return
}

s.logger.Debugf("unsupported interaction type received %s\n", callback.Type)
s.logger.Debug("unsupported interaction type", "type", callback.Type)
if s.unsupportedInteractionHandler != nil {
interactionCtx := newInteractionContext(ctx, s.logger, s.slackClient, callback, nil)
executeInteraction(interactionCtx, s.unsupportedInteractionHandler, middlewares...)
Expand Down Expand Up @@ -547,18 +547,18 @@ func (s *Slacker) ignoreBotMessage(messageEvent *MessageEvent) bool {
bot, err := s.slackClient.GetBotInfo(messageEvent.BotID)
if err != nil {
if err.Error() == "missing_scope" {
s.logger.Errorf("unable to determine if bot response is from me -- please add users:read scope to your app\n")
s.logger.Error("unable to determine if bot response is from me -- please add users:read scope to your app")
} else {
s.logger.Debugf("unable to get information on the bot that sent message: %v\n", err)
s.logger.Debug("unable to get information on the bot that sent message", "error", err)
}
return true
}
if bot.AppID == s.appID {
s.logger.Debugf("ignoring event that originated from my App ID: %v\n", bot.AppID)
s.logger.Debug("ignoring event that originated from my app", "app_id", bot.AppID)
return true
}
case BotModeIgnoreAll:
s.logger.Debugf("ignoring event that originated from Bot ID: %v\n", messageEvent.BotID)
s.logger.Debug("ignoring event that originated from bot", "bot_id", messageEvent.BotID)
return true
default:
// BotInteractionModeIgnoreNone is handled in the default case
Expand Down

0 comments on commit da0619f

Please sign in to comment.