diff --git a/bot/bot.go b/bot/bot.go index 102e19b..6fcd2a6 100644 --- a/bot/bot.go +++ b/bot/bot.go @@ -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 @@ -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) @@ -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, diff --git a/bot/command/joke.go b/bot/command/joke.go index 5b5504b..2c076f7 100644 --- a/bot/command/joke.go +++ b/bot/command/joke.go @@ -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" @@ -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(): @@ -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 } @@ -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] @@ -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 { @@ -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)) } } @@ -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 } @@ -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 @@ -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) diff --git a/bot/command/joke_test.go b/bot/command/joke_test.go index c2ecec6..e5fb6e2 100644 --- a/bot/command/joke_test.go +++ b/bot/command/joke_test.go @@ -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" @@ -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), @@ -43,6 +44,7 @@ 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), @@ -50,13 +52,13 @@ func TestFindJokeService_ContextCancelled(t *testing.T) { 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{}), } diff --git a/bot/command/list.go b/bot/command/list.go index 54393b6..543b429 100644 --- a/bot/command/list.go +++ b/bot/command/list.go @@ -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" @@ -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 @@ -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 @@ -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) { @@ -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) } } diff --git a/bot/command/response.go b/bot/command/response.go index bb373e0..a2c0f92 100644 --- a/bot/command/response.go +++ b/bot/command/response.go @@ -1,10 +1,8 @@ package command import ( - "context" "github.com/bwmarrin/discordgo" "github.com/wittano/komputer/bot/log" - "log/slog" ) const komputerMsgPrefix = "BEEP BOOP. " @@ -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) } } diff --git a/bot/command/spock.go b/bot/command/spock.go index ee5eb14..de051c8 100644 --- a/bot/command/spock.go +++ b/bot/command/spock.go @@ -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" ) @@ -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) { @@ -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 } diff --git a/bot/command/stop.go b/bot/command/stop.go index 30809c9..8d432aa 100644 --- a/bot/command/stop.go +++ b/bot/command/stop.go @@ -1,8 +1,8 @@ package command import ( - "context" "github.com/bwmarrin/discordgo" + "github.com/wittano/komputer/bot/log" "os" ) @@ -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) { diff --git a/bot/command/types.go b/bot/command/types.go index 66bfb13..50002b6 100644 --- a/bot/command/types.go +++ b/bot/command/types.go @@ -1,8 +1,8 @@ package command import ( - "context" "github.com/bwmarrin/discordgo" + "github.com/wittano/komputer/bot/log" ) const ( @@ -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 { diff --git a/bot/command/welcome.go b/bot/command/welcome.go index 980e817..e80db09 100644 --- a/bot/command/welcome.go +++ b/bot/command/welcome.go @@ -1,9 +1,9 @@ package command import ( - "context" "fmt" "github.com/bwmarrin/discordgo" + "github.com/wittano/komputer/bot/log" "os" "strings" ) @@ -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 } diff --git a/bot/joke/humorapi.go b/bot/joke/humorapi.go index 98ee576..a92aba3 100644 --- a/bot/joke/humorapi.go +++ b/bot/joke/humorapi.go @@ -9,7 +9,6 @@ import ( "github.com/wittano/komputer/internal" "github.com/wittano/komputer/internal/joke" "io" - "log/slog" "net/http" "os" "sync" @@ -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 @@ -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{} } diff --git a/bot/joke/humorapi_test.go b/bot/joke/humorapi_test.go index 8fc9478..8f6ad1a 100644 --- a/bot/joke/humorapi_test.go +++ b/bot/joke/humorapi_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "github.com/jarcoal/httpmock" + "github.com/wittano/komputer/bot/log" "github.com/wittano/komputer/internal" "github.com/wittano/komputer/internal/joke" "net/http" @@ -18,13 +19,6 @@ var ( Type: joke.Single, Category: joke.Any, } - testJoke = joke.DbModel{ - Question: "testQuestion", - Answer: "testAnswer", - Type: joke.Single, - Category: joke.Any, - GuildID: "", - } ) var testHumorAPIResponse = humorAPIResponse{ @@ -49,7 +43,7 @@ func TestHumorAPIService_Get(t *testing.T) { t.Fatal(err) } - ctx := context.Background() + ctx := log.NewContext(context.Background(), "") service := NewHumorAPIService(ctx) j, err := service.RandomJoke(ctx, testParams) @@ -67,7 +61,7 @@ func TestHumorAPIService_Get(t *testing.T) { } func TestHumorAPIService_GetWithMissingApiKey(t *testing.T) { - ctx := context.Background() + ctx := log.NewContext(context.Background(), "") service := NewHumorAPIService(ctx) if _, err := service.RandomJoke(ctx, testParams); err == nil { t.Fatal("service found API key, but it didn't set") @@ -93,9 +87,10 @@ func TestHumorAPIService_GetWithApiReturnInvalidStatus(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() + logCtx := log.NewContext(ctx, "") service := NewHumorAPIService(ctx) - if _, err := service.RandomJoke(ctx, testParams); err == nil { + if _, err := service.RandomJoke(logCtx, testParams); err == nil { t.Fatal("service didn't handle correct a bad/invalid http status") } }) @@ -114,7 +109,7 @@ func TestHumorAPIService_GetWithApiLimitExceeded(t *testing.T) { return } - ctx := context.Background() + ctx := log.NewContext(context.Background(), "") service := NewHumorAPIService(ctx) if _, err := service.RandomJoke(ctx, testParams); !errors.Is(err, HumorAPILimitExceededErr) { @@ -137,13 +132,14 @@ func TestHumorAPIService_Active(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - service := NewHumorAPIService(ctx) + logCtx := log.NewContext(ctx, "") + service := NewHumorAPIService(logCtx) - if _, err := service.RandomJoke(ctx, testParams); !errors.Is(err, HumorAPILimitExceededErr) { + if _, err := service.RandomJoke(logCtx, testParams); !errors.Is(err, HumorAPILimitExceededErr) { t.Fatal(err) } - if _, err := service.RandomJoke(ctx, testParams); !errors.Is(err, HumorAPILimitExceededErr) { + if _, err := service.RandomJoke(logCtx, testParams); !errors.Is(err, HumorAPILimitExceededErr) { t.Fatal(err) } diff --git a/bot/joke/jokedev.go b/bot/joke/jokedev.go index 170b0a1..fd462f7 100644 --- a/bot/joke/jokedev.go +++ b/bot/joke/jokedev.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/wittano/komputer/bot/log" "github.com/wittano/komputer/internal" "github.com/wittano/komputer/internal/joke" "io" @@ -91,7 +92,7 @@ func (d *DevService) Active(ctx context.Context) (active bool) { return } -func (d *DevService) RandomJoke(ctx context.Context, params internal.SearchParams) (joke.DbModel, error) { +func (d *DevService) RandomJoke(ctx log.Context, params internal.SearchParams) (joke.DbModel, error) { select { case <-ctx.Done(): return joke.DbModel{}, context.Canceled diff --git a/bot/joke/jokedev_test.go b/bot/joke/jokedev_test.go index a8aa44e..14e0cc9 100644 --- a/bot/joke/jokedev_test.go +++ b/bot/joke/jokedev_test.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "github.com/jarcoal/httpmock" + "github.com/wittano/komputer/bot/log" "github.com/wittano/komputer/internal/joke" "net/http" "os" @@ -43,7 +44,7 @@ func TestDevService_Get(t *testing.T) { return } - ctx := context.Background() + ctx := log.NewContext(context.Background(), "") service := NewJokeDevService(ctx) res, err := service.RandomJoke(ctx, testParams) @@ -79,9 +80,10 @@ func TestDevService_GetAndApiReturnInvalidStatus(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - service := NewJokeDevService(ctx) + logCtx := log.NewContext(ctx, "") + service := NewJokeDevService(logCtx) - if _, err := service.RandomJoke(ctx, testParams); err == nil { + if _, err := service.RandomJoke(logCtx, testParams); err == nil { t.Fatal("service didn't handle correct a bad/invalid http status") } }) @@ -100,7 +102,7 @@ func TestDevService_GetWithApiLimitExceeded(t *testing.T) { return } - ctx := context.Background() + ctx := log.NewContext(context.Background(), "") service := NewJokeDevService(ctx) if _, err := service.RandomJoke(ctx, testParams); !errors.Is(err, DevServiceLimitExceededErr) { @@ -119,15 +121,16 @@ func TestDevService_Active(t *testing.T) { os.Setenv(humorAPIKey, "123") ctx, cancel := context.WithCancel(context.Background()) + logCtx := log.NewContext(ctx, "") defer cancel() service := NewJokeDevService(ctx) - if _, err := service.RandomJoke(ctx, testParams); !errors.Is(err, DevServiceLimitExceededErr) { + if _, err := service.RandomJoke(logCtx, testParams); !errors.Is(err, DevServiceLimitExceededErr) { t.Fatal(err) } - if _, err := service.RandomJoke(ctx, testParams); !errors.Is(err, DevServiceLimitExceededErr) { + if _, err := service.RandomJoke(logCtx, testParams); !errors.Is(err, DevServiceLimitExceededErr) { t.Fatal(err) } diff --git a/bot/log/types.go b/bot/log/types.go index fd1cc1d..86942e3 100644 --- a/bot/log/types.go +++ b/bot/log/types.go @@ -11,21 +11,20 @@ const RequestIDKey = "requestID" type Func func(l slog.Logger) type Context struct { - // TODO Check out if I should change slog.Logger to zerolog.Logger Logger *slog.Logger - Ctx context.Context + ctx context.Context } func (c Context) Deadline() (deadline time.Time, ok bool) { - return c.Ctx.Deadline() + return c.ctx.Deadline() } func (c Context) Done() <-chan struct{} { - return c.Ctx.Done() + return c.ctx.Done() } func (c Context) Err() error { - return c.Ctx.Err() + return c.ctx.Err() } func (c Context) Value(key any) any { @@ -33,7 +32,7 @@ func (c Context) Value(key any) any { return c.Logger } - return c.Ctx.Value(key) + return c.ctx.Value(key) } // NewCtxWithRequestID returns new empty context with logger and requestID. @@ -44,20 +43,12 @@ func NewCtxWithRequestID(ctx context.Context) Context { requestID = "" } - return NewContext(requestID) + return NewContext(nil, requestID) } -func NewContext(uuid string) Context { +func NewContext(ctx context.Context, uuid string) Context { return Context{ slog.With(RequestIDKey, uuid), - context.WithValue(context.Background(), RequestIDKey, uuid), - } -} - -func Log(ctx context.Context, logFunc Func) { - if loggerCtx, ok := ctx.(Context); ok { - logFunc(*loggerCtx.Logger) - } else { - logFunc(*slog.Default()) + context.WithValue(ctx, RequestIDKey, uuid), } } diff --git a/internal/mongodb/database.go b/internal/mongodb/database.go index 50cdbc0..ad64483 100644 --- a/internal/mongodb/database.go +++ b/internal/mongodb/database.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/wittano/komputer/bot/log" "github.com/wittano/komputer/internal" "github.com/wittano/komputer/internal/joke" "go.mongodb.org/mongo-driver/bson" @@ -62,7 +63,7 @@ func (d Service) Add(ctx context.Context, joke joke.DbModel) (string, error) { return res.InsertedID.(primitive.ObjectID).Hex(), nil } -func (d Service) RandomJoke(ctx context.Context, search internal.SearchParams) (joke.DbModel, error) { +func (d Service) RandomJoke(ctx log.Context, search internal.SearchParams) (joke.DbModel, error) { jokes, err := d.Jokes(ctx, search) if err != nil { return joke.DbModel{}, err diff --git a/internal/types.go b/internal/types.go index 7d4a23a..eb91efa 100644 --- a/internal/types.go +++ b/internal/types.go @@ -2,6 +2,7 @@ package internal import ( "context" + "github.com/wittano/komputer/bot/log" "github.com/wittano/komputer/internal/joke" "go.mongodb.org/mongo-driver/bson/primitive" ) @@ -12,7 +13,7 @@ type AddService interface { type SearchService interface { // RandomJoke Joke Try to find Joke from Db database. If SearchParams is empty, then function will find 1 random joke - RandomJoke(ctx context.Context, search SearchParams) (joke.DbModel, error) + RandomJoke(ctx log.Context, search SearchParams) (joke.DbModel, error) ActiveChecker }