Skip to content
This repository has been archived by the owner on Dec 25, 2024. It is now read-only.

Commit

Permalink
fix(log): replaced default context by logger context
Browse files Browse the repository at this point in the history
  • Loading branch information
Wittano committed Aug 22, 2024
1 parent 0759396 commit 7fee001
Show file tree
Hide file tree
Showing 16 changed files with 74 additions and 103 deletions.
26 changes: 9 additions & 17 deletions bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ func (sc slashCommandHandler) handleSlashCommand(s *discordgo.Session, i *discor
const cmdTimeout = time.Second * 2

requestID := uuid.New().String()
loggerCtx := log.NewContext(requestID)
deadlineCtx, cancel := context.WithTimeout(loggerCtx, cmdTimeout)
ctx := context.WithValue(deadlineCtx, mongodb.GuildIDKey, i.GuildID)
deadlineCtx, cancel := context.WithTimeout(sc.ctx, cmdTimeout)
defer cancel()
valueCtx := context.WithValue(deadlineCtx, mongodb.GuildIDKey, i.GuildID)
ctx := log.NewContext(valueCtx, requestID)

userID := i.Member.User.ID
// Handle options assigned to slash commands
Expand All @@ -45,9 +45,7 @@ func (sc slashCommandHandler) handleSlashCommand(s *discordgo.Session, i *discor

for _, option := range sc.options {
if matcher, ok := option.(command.DiscordOptionMatcher); ok && matcher.Match(customID) {
log.Log(ctx, func(log slog.Logger) {
log.InfoContext(ctx, fmt.Sprintf("user '%s' select '%s' option", userID, customID))
})
ctx.Logger.InfoContext(ctx, fmt.Sprintf("user '%s' select '%s' option", userID, customID))

handleEventResponse(ctx, s, i, option)

Expand All @@ -59,37 +57,31 @@ func (sc slashCommandHandler) handleSlashCommand(s *discordgo.Session, i *discor
defer func() {
if r := recover(); r != nil {
cancel()
log.Log(ctx, func(log slog.Logger) {
log.Error("unexpected error during handle command", r)
})
ctx.Logger.Error("unexpected error during handle command", r)
}
}()

// Handle slash commands
name := i.ApplicationCommandData().Name
if cmd, ok := sc.commands[name]; ok {
log.Log(ctx, func(l slog.Logger) {
l.InfoContext(ctx, fmt.Sprintf("user '%s' execute slash command '%s'", userID, name))
})
ctx.Logger.InfoContext(ctx, fmt.Sprintf("user '%s' execute slash command '%s'", userID, name))

handleEventResponse(ctx, s, i, cmd)
} else {
msg := command.SimpleMessage{Msg: "Kapitanie co chcesz zrobić?", Hidden: true}

log.Log(ctx, func(l slog.Logger) {
l.WarnContext(ctx, "someone try execute unknown command")
})
ctx.Logger.WarnContext(ctx, "someone try execute unknown command")
command.CreateDiscordInteractionResponse(ctx, i, s, msg)
}
}

func handleEventResponse(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate, event command.DiscordEventHandler) {
func handleEventResponse(ctx log.Context, s *discordgo.Session, i *discordgo.InteractionCreate, event command.DiscordEventHandler) {
msg, err := event.Execute(ctx, s, i)

if errors.Is(err, command.DiscordError{}) {
errors.As(err, &msg)
} else if err != nil {
ctx.(log.Context).Logger.ErrorContext(ctx, err.Error())
ctx.Logger.ErrorContext(ctx, err.Error())

msg = command.DiscordError{
Err: err,
Expand Down
21 changes: 8 additions & 13 deletions bot/command/joke.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/joke"
"go.mongodb.org/mongo-driver/bson/primitive"
"log/slog"
"math/rand"
"os"
"slices"
Expand Down Expand Up @@ -54,11 +53,9 @@ func (j JokeCommand) Command() *discordgo.ApplicationCommand {
}
}

func (j JokeCommand) Execute(ctx context.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (j JokeCommand) Execute(ctx log.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
searchQuery := searchParams(ctx, i.Data.(discordgo.ApplicationCommandInteractionData))

loggerCtx := ctx.(log.Context)

findJoke:
select {
case <-ctx.Done():
Expand All @@ -73,7 +70,7 @@ findJoke:

res, err := service.RandomJoke(ctx, searchQuery)
if err != nil {
loggerCtx.Logger.Error(err.Error())
ctx.Logger.Error(err.Error())
goto findJoke
}

Expand All @@ -83,7 +80,7 @@ findJoke:
}, nil
}

func findService(ctx context.Context, services []internal.SearchService) (internal.SearchService, error) {
func findService(ctx log.Context, services []internal.SearchService) (internal.SearchService, error) {
if len(services) == 1 {
service := services[0]

Expand All @@ -110,7 +107,7 @@ func findService(ctx context.Context, services []internal.SearchService) (intern
}

// Get internal.SearchParams from Discord options
func searchParams(ctx context.Context, data discordgo.ApplicationCommandInteractionData) (query internal.SearchParams) {
func searchParams(ctx log.Context, data discordgo.ApplicationCommandInteractionData) (query internal.SearchParams) {
query.Type, query.Category = joke.Single, joke.Any

for _, o := range data.Options {
Expand All @@ -122,9 +119,7 @@ func searchParams(ctx context.Context, data discordgo.ApplicationCommandInteract
case idOptionKey:
query.ID = o.Value.(primitive.ObjectID)
default:
log.Log(ctx, func(log slog.Logger) {
log.Warn(fmt.Sprintf("Invalid searchOption for %s", o.Name))
})
ctx.Logger.Warn(fmt.Sprintf("Invalid searchOption for %s", o.Name))
}
}

Expand Down Expand Up @@ -299,7 +294,7 @@ func (a ApologiesOption) Match(customID string) bool {
return customID == ApologiesButtonName
}

func (a ApologiesOption) Execute(_ context.Context, _ *discordgo.Session, _ *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (a ApologiesOption) Execute(_ log.Context, _ *discordgo.Session, _ *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
return SimpleMessage{Msg: "Przepraszam"}, nil
}

Expand All @@ -311,7 +306,7 @@ func (n NextJokeOption) Match(customID string) bool {
return customID == NextJokeButtonName
}

func (n NextJokeOption) Execute(ctx context.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (n NextJokeOption) Execute(ctx log.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
service, err := findService(ctx, n.Services)
if err != nil {
return nil, err
Expand Down Expand Up @@ -342,7 +337,7 @@ func (s SameJokeCategoryOption) Match(customID string) bool {
return customID == SameJokeCategoryButtonName
}

func (s SameJokeCategoryOption) Execute(ctx context.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (s SameJokeCategoryOption) Execute(ctx log.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
fields := i.Message.Embeds[0].Fields
category := joke.Category(fields[len(fields)-1].Value)

Expand Down
8 changes: 5 additions & 3 deletions bot/command/joke_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"github.com/wittano/komputer/bot/joke"
"github.com/wittano/komputer/bot/log"
"github.com/wittano/komputer/internal"
"go.mongodb.org/mongo-driver/mongo"
"testing"
Expand All @@ -20,7 +21,7 @@ func (d dumpMongoService) Client(_ context.Context) (*mongo.Client, error) {
}

func TestSelectGetService(t *testing.T) {
ctx := context.Background()
ctx := log.NewContext(context.Background(), "")
testServices := []internal.SearchService{
joke.NewJokeDevService(ctx),
joke.NewHumorAPIService(ctx),
Expand All @@ -43,20 +44,21 @@ func TestSelectGetService(t *testing.T) {

func TestFindJokeService_ContextCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
logCtx := log.NewContext(ctx, "")
cancel()
testServices := []internal.SearchService{
joke.NewJokeDevService(ctx),
joke.NewHumorAPIService(ctx),
joke.NewJokeDatabase(dumpMongoService{}),
}

if _, err := findService(ctx, testServices); err == nil {
if _, err := findService(logCtx, testServices); err == nil {
t.Fatal("Some services was found, but shouldn't")
}
}

func TestFindJokeService_ServicesIsDeactivated(t *testing.T) {
ctx := context.Background()
ctx := log.NewContext(context.Background(), "")
services := []internal.SearchService{
joke.NewJokeDatabase(dumpMongoService{}),
}
Expand Down
9 changes: 5 additions & 4 deletions bot/command/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/bot/log"
"github.com/wittano/komputer/internal/audio"
"os"
"regexp"
Expand Down Expand Up @@ -94,7 +95,7 @@ func (n NextListCommandOption) Match(customID string) bool {
return regexp.MustCompile(fmt.Sprintf("^%s_(a-z0-9)*", nextIdsButtonID)).MatchString(customID)
}

func (n NextListCommandOption) Execute(ctx context.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (n NextListCommandOption) Execute(ctx log.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
select {
case <-ctx.Done():
return nil, context.Canceled
Expand Down Expand Up @@ -130,7 +131,7 @@ func (p PreviousListCommandOption) Match(customID string) bool {
return regexp.MustCompile(fmt.Sprintf("^%s_(a-z0-9)*", previousIdsButtonID)).MatchString(customID)
}

func (p PreviousListCommandOption) Execute(ctx context.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (p PreviousListCommandOption) Execute(ctx log.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
select {
case <-ctx.Done():
return nil, context.Canceled
Expand Down Expand Up @@ -189,7 +190,7 @@ func (l ListCommand) Command() *discordgo.ApplicationCommand {
}

func (l ListCommand) Execute(
ctx context.Context,
ctx log.Context,
_ *discordgo.Session,
i *discordgo.InteractionCreate,
) (DiscordMessageReceiver, error) {
Expand All @@ -213,7 +214,7 @@ func (l *ListCommand) update(size int, userID string, direction pageDirection) {

if size == 0 || l.pageCounter[userID] < 0 {
l.pageCounter[userID] = 0
} else if size != 0 && l.pageCounter[userID] >= 0 {
} else if l.pageCounter[userID] >= 0 {
l.pageCounter[userID] += int(direction)
}
}
Expand Down
8 changes: 2 additions & 6 deletions bot/command/response.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package command

import (
"context"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/bot/log"
"log/slog"
)

const komputerMsgPrefix = "BEEP BOOP. "
Expand Down Expand Up @@ -45,13 +43,11 @@ func (s SimpleMessage) Response() (msg *discordgo.InteractionResponseData) {
return
}

func CreateDiscordInteractionResponse(ctx context.Context, i *discordgo.InteractionCreate, s *discordgo.Session, msg DiscordMessageReceiver) {
func CreateDiscordInteractionResponse(ctx log.Context, i *discordgo.InteractionCreate, s *discordgo.Session, msg DiscordMessageReceiver) {
if err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: msg.Response(),
}); err != nil {
log.Log(ctx, func(l slog.Logger) {
l.Error("failed send response to discord user", "error", err)
})
ctx.Logger.Error("failed send response to discord user", "error", err)
}
}
13 changes: 4 additions & 9 deletions bot/command/spock.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import (
"fmt"
"github.com/bwmarrin/dgvoice"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/internal/audio"
"github.com/wittano/komputer/bot/log"
"github.com/wittano/komputer/bot/voice"
"log/slog"
"github.com/wittano/komputer/internal/audio"
"os"
)

Expand Down Expand Up @@ -41,7 +40,7 @@ func (sc SpockCommand) Command() *discordgo.ApplicationCommand {
}

func (sc SpockCommand) Execute(
ctx context.Context,
ctx log.Context,
s *discordgo.Session,
i *discordgo.InteractionCreate,
) (DiscordMessageReceiver, error) {
Expand All @@ -54,18 +53,14 @@ func (sc SpockCommand) Execute(

info, ok := sc.GuildVoiceChats[i.GuildID]
if !ok || info.UserCount == 0 {
log.Log(ctx, func(l slog.Logger) {
l.Error(fmt.Sprintf(fmt.Sprintf("user with ID '%s' wasn't found on any voice chat on '%s' server", i.Member.User.ID, i.GuildID)))
})
ctx.Logger.Error(fmt.Sprintf(fmt.Sprintf("user with ID '%s' wasn't found on any voice chat on '%s' server", i.Member.User.ID, i.GuildID)))

return SimpleMessage{Msg: "Kapitanie gdzie jesteś? Wejdź na kanał głosowy a ja dołącze"}, nil
}

path, err := audioPath(i.Data.(discordgo.ApplicationCommandInteractionData))
if err != nil {
log.Log(ctx, func(l slog.Logger) {
l.Error("failed find song path", "error", err)
})
ctx.Logger.Error("failed find song path", "error", err)

return SimpleMessage{Msg: "Panie kapitanie, nie znalazłem utworu"}, nil
}
Expand Down
4 changes: 2 additions & 2 deletions bot/command/stop.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package command

import (
"context"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/bot/log"
"os"
)

Expand All @@ -22,7 +22,7 @@ func (sc StopCommand) Command() *discordgo.ApplicationCommand {
}

func (sc StopCommand) Execute(
ctx context.Context,
ctx log.Context,
s *discordgo.Session,
i *discordgo.InteractionCreate,
) (res DiscordMessageReceiver, _ error) {
Expand Down
4 changes: 2 additions & 2 deletions bot/command/types.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package command

import (
"context"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/bot/log"
)

const (
Expand All @@ -15,7 +15,7 @@ type DiscordSlashCommandHandler interface {
}

type DiscordEventHandler interface {
Execute(ctx context.Context, s *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error)
Execute(ctx log.Context, s *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error)
}

type DiscordOptionMatcher interface {
Expand Down
4 changes: 2 additions & 2 deletions bot/command/welcome.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package command

import (
"context"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/bot/log"
"os"
"strings"
)
Expand All @@ -21,6 +21,6 @@ func (w WelcomeCommand) Command() *discordgo.ApplicationCommand {
}
}

func (w WelcomeCommand) Execute(_ context.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
func (w WelcomeCommand) Execute(_ log.Context, _ *discordgo.Session, i *discordgo.InteractionCreate) (DiscordMessageReceiver, error) {
return SimpleMessage{Msg: fmt.Sprintf("Witaj panie %s kapitanie! W czym mogę pomóc?", strings.ToUpper(i.Member.User.Username))}, nil
}
7 changes: 2 additions & 5 deletions bot/joke/humorapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/joke"
"io"
"log/slog"
"net/http"
"os"
"sync"
Expand Down Expand Up @@ -47,7 +46,7 @@ func (h *HumorAPIService) Active(ctx context.Context) (active bool) {
return
}

func (h *HumorAPIService) RandomJoke(ctx context.Context, search internal.SearchParams) (joke.DbModel, error) {
func (h *HumorAPIService) RandomJoke(ctx log.Context, search internal.SearchParams) (joke.DbModel, error) {
select {
case <-ctx.Done():
return joke.DbModel{}, context.Canceled
Expand Down Expand Up @@ -91,9 +90,7 @@ func (h *HumorAPIService) RandomJoke(ctx context.Context, search internal.Search
} else if res.StatusCode != http.StatusOK {
msg, err := io.ReadAll(res.Body)
if err != nil {
log.Log(ctx, func(l slog.Logger) {
l.ErrorContext(ctx, "humorAPI: failed read response body", "error", err)
})
ctx.Logger.ErrorContext(ctx, "humorAPI: failed read response body", "error", err)
msg = []byte{}
}

Expand Down
Loading

0 comments on commit 7fee001

Please sign in to comment.