Skip to content

Commit

Permalink
Use slog logger.
Browse files Browse the repository at this point in the history
  • Loading branch information
onrik committed Aug 12, 2024
1 parent 2cd2a87 commit d10c6d9
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 15 deletions.
5 changes: 3 additions & 2 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
)
Expand Down Expand Up @@ -37,7 +38,7 @@ func NewBot(token string, opts ...Option) (*Bot, error) {
options := Options{
limit: 100,
timeout: 25,
logger: newLogger("[micha] "),
logger: slog.Default(),
apiServer: defaultAPIServer,
httpClient: http.DefaultClient,
ctx: context.Background(),
Expand Down Expand Up @@ -178,7 +179,7 @@ func (bot *Bot) Start(allowedUpdates ...string) {
for {
updates, err := bot.getUpdates(bot.offset+1, allowedUpdates...)
if err != nil {
bot.logger.Printf("Get updates error (%s)\n", err.Error())
bot.logger.ErrorContext(bot.ctx, "Get updates error", "error", err)
}

for _, update := range updates {
Expand Down
8 changes: 4 additions & 4 deletions bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"context"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/url"
"os"
Expand All @@ -30,7 +30,7 @@ func (s *BotTestSuite) SetupSuite() {
Options: Options{
limit: 100,
timeout: 25,
logger: newLogger("micha"),
logger: slog.Default(),
apiServer: defaultAPIServer,
httpClient: http.DefaultClient,
},
Expand Down Expand Up @@ -132,10 +132,10 @@ func (s *BotTestSuite) TestNewBot() {
s.Require().NotNil(bot)
s.Require().Equal(25, bot.timeout)
s.Require().Equal(100, bot.limit)
s.Require().Equal(newLogger("[micha] "), bot.logger)
s.Require().Equal(slog.Default(), bot.logger)

// With options
logger := log.New(os.Stderr, "", log.LstdFlags)
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
httpClient := &http.Client{}
bot, err = NewBot("111", WithLimit(50), WithTimeout(10), WithLogger(logger), WithHttpClient(httpClient))
s.Require().Nil(err)
Expand Down
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/onrik/micha

go 1.19
go 1.22

require (
github.com/jarcoal/httpmock v1.3.1
Expand Down
10 changes: 2 additions & 8 deletions logger.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
package micha

import (
"log"
"os"
"context"
)

// Logger interface
type Logger interface {
Println(v ...interface{})
Printf(format string, v ...interface{})
}

func newLogger(prefix string) Logger {
return log.New(os.Stderr, prefix, log.Ldate|log.Ltime|log.Lshortfile)
ErrorContext(ctx context.Context, msg string, args ...any)
}

0 comments on commit d10c6d9

Please sign in to comment.