Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support slog Logger #155

Closed
wants to merge 14 commits into from
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Built on top of the Slack API [github.com/slack-go/slack](https://github.com/sla
- Replies can be new messages or in threads
- Replies can be ephemeral, scheduled, updated or deleted
- Supports Slash Commands and Interactive Messages
- Supports `slog.Logger`
- Supports `context.Context`
- Supports middlewares & grouping of commands
- Supports Cron Jobs using [https://github.com/robfig/cron](https://github.com/robfig/cron)
Expand Down Expand Up @@ -86,5 +87,5 @@ an issue with Slacker or wish to contribute to the project.
There are a few common issues that can cause this:

* The OAuth (bot) Token may be incorrect. In this case authentication does not fail like it does if the App Token is incorrect, and the bot will simply have no scopes and be unable to respond.
* Required scopes are missing from the OAuth (bot) Token. Similar to the incorrect OAuth Token, without the necessary scopes, the bot cannot respond.
* Required scopes are missing from the OAuth (bot) Token. Similar to the incorrect OAuth Token, without the necessary scopes, the bot can not respond.
* The bot does not have the correct event subscriptions setup, and is not receiving events to respond to.
4 changes: 2 additions & 2 deletions examples/interaction-middleware/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ 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.Logger().Info(
"%s initiated \"%s\" with action \"%v\" in channel %s",
raed-shomali marked this conversation as resolved.
Show resolved Hide resolved
ctx.Callback().User.ID,
ctx.Definition().BlockID,
ctx.Callback().ActionCallback.BlockActions[0].ActionID,
Expand Down
8 changes: 4 additions & 4 deletions examples/job-middleware/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ 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.Logger().Info(
"%s started",
ctx.Definition().Name,
)
next(ctx)
ctx.Logger().Infof(
"%s ended\n",
ctx.Logger().Info(
"%s ended",
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"

Check failure on line 4 in logger.go

View workflow job for this annotation

GitHub Actions / runner / staticcheck

[staticcheck] reported by reviewdog 🐶 package log/slog is not in GOROOT (/opt/hostedtoolcache/go/1.20.10/x64/src/log/slog) note: imported by a module that requires go 1.21 Raw Output: {"source":{"name":"staticcheck","url":"https://staticcheck.io"},"message":"package log/slog is not in GOROOT (/opt/hostedtoolcache/go/1.20.10/x64/src/log/slog)\nnote: imported by a module that requires go 1.21","code":{"value":"compile","url":"https://staticcheck.io/docs/checks#compile"},"location":{"path":"logger.go","range":{"start":{"line":4,"column":2}}},"severity":"ERROR"}
"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 for %s: %v", channelID, 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 for %s: %v", userID, 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: %v", 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: %v", err)
}
return timestamp, err
}
32 changes: 16 additions & 16 deletions slacker.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,23 +216,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 @@ -241,15 +241,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 as App ID %v", 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 due to %v", socketEvent.Request.Reason)

if s.onDisconnected == nil {
continue
Expand All @@ -259,7 +259,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 %+v", socketEvent)
continue
}

Expand All @@ -270,7 +270,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 received %+v", socketEvent)
}
continue
}
Expand All @@ -283,14 +283,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 received %+v", socketEvent)
}
}

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

Expand All @@ -302,7 +302,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 %+v", socketEvent)
continue
}

Expand All @@ -315,7 +315,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 received %+v", socketEvent)
}
}
}
Expand Down Expand Up @@ -425,7 +425,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 @@ -504,18 +504,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: %v", 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 ID: %v", 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 ID: %v", messageEvent.BotID)
return true
default:
// BotInteractionModeIgnoreNone is handled in the default case
Expand Down
Loading