Skip to content

Commit

Permalink
switch to slog
Browse files Browse the repository at this point in the history
  • Loading branch information
rusq committed Nov 18, 2024
1 parent 579dafe commit 2fc218d
Show file tree
Hide file tree
Showing 75 changed files with 360 additions and 442 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ Slackdump uses a simple [rusq/dlog][dlog] as a default logger (it is a wrapper a
the standard logger that adds `Debug*` functions).

If you want to use the same default logger that Slackdump uses in your
application, it is available as `logger.Default`.
application, it is available as `slog.Default()`.

No doubts that everyone has their own favourite logger that is better than other
miserable loggers. Please read below for instructions on plugging your
Expand Down
27 changes: 12 additions & 15 deletions auth/browser/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"runtime"
Expand All @@ -13,7 +14,6 @@ import (

"github.com/playwright-community/playwright-go"
"github.com/rusq/slackdump/v3/auth/browser/pwcompat"
"github.com/rusq/slackdump/v3/logger"
)

const (
Expand All @@ -30,7 +30,7 @@ type Client struct {
verbose bool
}

var Logger logger.Interface = logger.Default
var Logger = slog.Default()

var (
installFn = playwright.Install
Expand All @@ -51,7 +51,7 @@ func New(workspace string, opts ...Option) (*Client, error) {
for _, opt := range opts {
opt(cl)
}
l().Debugf("browser=%s, timeout=%f", cl.br, cl.loginTimeout)
slog.Debug("New", "workspace", cl.workspace, "browser", cl.br, "timeout", cl.loginTimeout)
runopts := &playwright.RunOptions{
Browsers: []string{cl.br.String()},
Verbose: cl.verbose,
Expand All @@ -77,13 +77,14 @@ func (cl *Client) Authenticate(ctx context.Context) (string, []*http.Cookie, err
_b = playwright.Bool
)

lg := slog.Default()
pw, err := playwright.Run()
if err != nil {
return "", nil, err
}
defer func() {
if err := pw.Stop(); err != nil {
l().Printf("failed to stop playwright: %v", err)
lg.ErrorContext(ctx, "failed to stop playwright", "error", err)
}
}()

Expand Down Expand Up @@ -124,7 +125,7 @@ func (cl *Client) Authenticate(ctx context.Context) (string, []*http.Cookie, err
page.On("close", func() { trace.Log(ctx, "user", "page closed"); close(cl.pageClosed) })

uri := fmt.Sprintf("https://%s"+slackDomain, cl.workspace)
l().Debugf("opening browser URL=%s", uri)
lg.Debug("opening browser", "URL", uri)

if _, err := page.Goto(uri); err != nil {
return "", nil, err
Expand Down Expand Up @@ -219,13 +220,6 @@ func float2time(v float64) time.Time {
return time.Unix(int64(v), 0)
}

func l() logger.Interface {
if Logger == nil {
return logger.Default
}
return Logger
}

// pwRepair attempts to repair the playwright installation.
func pwRepair(runopts *playwright.RunOptions) error {
ad, err := pwcompat.NewAdapter(runopts)
Expand All @@ -249,18 +243,21 @@ func Reinstall(browser Browser, verbose bool) error {
}

func reinstall(runopts *playwright.RunOptions) error {
l().Debugf("reinstalling browser: %s", runopts.Browsers[0])
lg := slog.With("browser", runopts.Browsers[0])

lg.Debug("reinstalling browser")
ad, err := pwcompat.NewAdapter(runopts)
if err != nil {
return err
}
l().Debugf("removing %s", ad.DriverDirectory)
lg = lg.With("driver_directory", ad.DriverDirectory)
lg.Debug("removing driver directory")
if err := os.RemoveAll(ad.DriverDirectory); err != nil {
return err
}

// attempt to reinstall
l().Debugf("reinstalling %s", ad.DriverDirectory)
lg.Debug("reinstalling")
if err := installFn(runopts); err != nil {
// we did everything we could, but it still failed.
return err
Expand Down
8 changes: 4 additions & 4 deletions auth/rod.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"log/slog"
"os"
"time"

Expand All @@ -12,7 +13,6 @@ import (

"github.com/rusq/slackdump/v3/auth/auth_ui"
"github.com/rusq/slackdump/v3/internal/structures"
"github.com/rusq/slackdump/v3/logger"
)

// RODHeadlessTimeout is the default timeout for the headless login flow.
Expand Down Expand Up @@ -116,12 +116,12 @@ func NewRODAuth(ctx context.Context, opts ...Option) (RodAuth, error) {
}
defer cl.Close()

lg := logger.FromContext(ctx)
lg := slog.Default()
t := time.Now()
var sp simpleProvider
switch resp.Type {
case auth_ui.LInteractive, auth_ui.LUserBrowser:
lg.Printf("ℹ️ Initialising browser, once the browser appears, login as usual")
lg.InfoContext(ctx, "ℹ️ Initialising browser, once the browser appears, login as usual")
var err error
sp.Token, sp.Cookie, err = cl.Manual(ctx)
if err != nil {
Expand All @@ -135,7 +135,7 @@ func NewRODAuth(ctx context.Context, opts ...Option) (RodAuth, error) {
case auth_ui.LCancel:
return r, ErrCancelled
}
lg.Printf("✅ authenticated (time taken: %s)", time.Since(t))
lg.InfoContext(ctx, "✅ authenticated", "time_taken", time.Since(t).String())

return RodAuth{
simpleProvider: sp,
Expand Down
9 changes: 4 additions & 5 deletions channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,13 @@ func (s *Session) getChannels(ctx context.Context, chanTypes []string, cb func(t
}
total += len(chans)

s.log.Printf("channels request #%5d, fetched: %4d, total: %8d (speed: %6.2f/sec, avg: %6.2f/sec)\n",
i, len(chans), total,
float64(len(chans))/float64(time.Since(reqStart).Seconds()),
float64(total)/float64(time.Since(fetchStart).Seconds()),
s.log.InfoContext(ctx, "channels", "request", i, "fetched", len(chans), "total", total,
"speed", float64(len(chans))/time.Since(reqStart).Seconds(),
"avg", float64(total)/time.Since(fetchStart).Seconds(),
)

if nextcur == "" {
s.log.Printf("channels fetch complete, total: %d channels", total)
s.log.InfoContext(ctx, "channels fetch complete", "total", total)
break
}

Expand Down
4 changes: 2 additions & 2 deletions channels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package slackdump
import (
"context"
"errors"
"log/slog"
"reflect"
"testing"

Expand All @@ -11,7 +12,6 @@ import (
"go.uber.org/mock/gomock"

"github.com/rusq/slackdump/v3/internal/network"
"github.com/rusq/slackdump/v3/logger"
"github.com/rusq/slackdump/v3/types"
)

Expand Down Expand Up @@ -80,7 +80,7 @@ func TestSession_getChannels(t *testing.T) {
sd := &Session{
client: mc,
cfg: tt.fields.config,
log: logger.Silent,
log: slog.Default(),
}

if tt.expectFn != nil {
Expand Down
10 changes: 5 additions & 5 deletions cmd/slackdump/internal/archive/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
_ "embed"
"errors"
"log/slog"
"time"

"github.com/rusq/fsadapter"
Expand All @@ -14,7 +15,6 @@ import (
"github.com/rusq/slackdump/v3/internal/chunk/control"
"github.com/rusq/slackdump/v3/internal/chunk/transform/fileproc"
"github.com/rusq/slackdump/v3/internal/structures"
"github.com/rusq/slackdump/v3/logger"
"github.com/rusq/slackdump/v3/stream"
)

Expand Down Expand Up @@ -63,7 +63,7 @@ func RunArchive(ctx context.Context, cmd *base.Command, args []string) error {
base.SetExitStatus(base.SInitializationError)
return err
}
lg := logger.FromContext(ctx)
lg := cfg.Log
stream := sess.Stream(
stream.OptLatest(time.Time(cfg.Latest)),
stream.OptOldest(time.Time(cfg.Oldest)),
Expand All @@ -84,14 +84,14 @@ func RunArchive(ctx context.Context, cmd *base.Command, args []string) error {
base.SetExitStatus(base.SApplicationError)
return err
}
lg.Printf("Recorded workspace data to %s", cd.Name())
lg.Info("Recorded workspace data", "filename", cd.Name())

return nil
}

func resultLogger(lg logger.Interface) func(sr stream.Result) error {
func resultLogger(lg *slog.Logger) func(sr stream.Result) error {
return func(sr stream.Result) error {
lg.Printf("%s", sr)
lg.Info("stream", "result", sr.String())
return nil
}
}
4 changes: 2 additions & 2 deletions cmd/slackdump/internal/archive/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package archive
import (
"context"
"errors"
"log/slog"
"strings"

"github.com/rusq/fsadapter"
Expand All @@ -12,7 +13,6 @@ import (
"github.com/rusq/slackdump/v3/internal/chunk"
"github.com/rusq/slackdump/v3/internal/chunk/control"
"github.com/rusq/slackdump/v3/internal/chunk/transform/fileproc"
"github.com/rusq/slackdump/v3/logger"
"github.com/rusq/slackdump/v3/stream"
)

Expand Down Expand Up @@ -134,7 +134,7 @@ func initController(ctx context.Context, args []string) (*control.Controller, fu
}
defer cd.Close()

lg := logger.FromContext(ctx)
lg := slog.Default()
dl, stop := fileproc.NewDownloader(
ctx,
cfg.DownloadFiles,
Expand Down
5 changes: 2 additions & 3 deletions cmd/slackdump/internal/cfg/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package cfg
import (
"flag"
"fmt"
"log/slog"
"os"
"time"

Expand All @@ -12,7 +13,6 @@ import (
"github.com/rusq/slackdump/v3/auth"
"github.com/rusq/slackdump/v3/auth/browser"
"github.com/rusq/slackdump/v3/internal/network"
"github.com/rusq/slackdump/v3/logger"
)

const (
Expand Down Expand Up @@ -55,8 +55,7 @@ var (
UserCacheRetention time.Duration
NoUserCache bool

Log logger.Interface

Log *slog.Logger = slog.Default()
// LoadSecrets is a flag that indicates whether to load secrets from the
// environment variables.
LoadSecrets bool
Expand Down
9 changes: 4 additions & 5 deletions cmd/slackdump/internal/convertcmd/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/rusq/slackdump/v3/internal/chunk"
"github.com/rusq/slackdump/v3/internal/chunk/transform/fileproc"
"github.com/rusq/slackdump/v3/internal/convert"
"github.com/rusq/slackdump/v3/logger"
)

var CmdConvert = &base.Command{
Expand Down Expand Up @@ -60,8 +59,8 @@ func runConvert(ctx context.Context, cmd *base.Command, args []string) error {
return errors.New("unsupported conversion type")
}

lg := logger.FromContext(ctx)
lg.Printf("converting (%s) %q to (%s) %q", params.inputfmt, args[0], params.outputfmt, cfg.Output)
lg := cfg.Log
lg.InfoContext(ctx, "converting", "input_format", params.inputfmt, "source", args[0], "output_format", params.outputfmt, "output", cfg.Output)

cflg := convertflags{
withFiles: cfg.DownloadFiles,
Expand All @@ -73,7 +72,7 @@ func runConvert(ctx context.Context, cmd *base.Command, args []string) error {
return err
}

lg.Printf("completed in %s", time.Since(start))
lg.InfoContext(ctx, "completed", "took", time.Since(start))
return nil
}

Expand Down Expand Up @@ -123,7 +122,7 @@ func chunk2export(ctx context.Context, src, trg string, cflg convertflags) error
fsa,
convert.WithIncludeFiles(cflg.withFiles),
convert.WithTrgFileLoc(sttFn),
convert.WithLogger(logger.FromContext(ctx)),
convert.WithLogger(cfg.Log),
)
if err := cvt.Convert(ctx); err != nil {
return err
Expand Down
10 changes: 5 additions & 5 deletions cmd/slackdump/internal/diag/edge.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"os"

"github.com/rusq/slackdump/v3/auth"
"github.com/rusq/slackdump/v3/cmd/slackdump/internal/cfg"
"github.com/rusq/slackdump/v3/cmd/slackdump/internal/golang/base"
"github.com/rusq/slackdump/v3/internal/edge"
"github.com/rusq/slackdump/v3/logger"
)

var CmdEdge = &base.Command{
Expand All @@ -33,7 +33,7 @@ func init() {
}

func runEdge(ctx context.Context, cmd *base.Command, args []string) error {
lg := logger.FromContext(ctx)
lg := cfg.Log

prov, err := auth.FromContext(ctx)
if err != nil {
Expand All @@ -47,9 +47,9 @@ func runEdge(ctx context.Context, cmd *base.Command, args []string) error {
return err
}
defer cl.Close()
lg.Print("connected")
lg.Info("connected")

lg.Printf("*** Search for Channels test ***")
lg.Info("*** Search for Channels test ***")
channels, err := cl.SearchChannels(ctx, "")
if err != nil {
return err
Expand Down Expand Up @@ -115,7 +115,7 @@ func runEdge(ctx context.Context, cmd *base.Command, args []string) error {
// }
// }

lg.Print("OK")
lg.Info("OK")
return nil
}

Expand Down
8 changes: 4 additions & 4 deletions cmd/slackdump/internal/diag/eztest.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
"github.com/playwright-community/playwright-go"

"github.com/rusq/slackdump/v3/auth"
"github.com/rusq/slackdump/v3/cmd/slackdump/internal/cfg"
"github.com/rusq/slackdump/v3/cmd/slackdump/internal/golang/base"
"github.com/rusq/slackdump/v3/logger"
)

var CmdEzTest = &base.Command{
Expand Down Expand Up @@ -65,7 +65,7 @@ func init() {
}

func runEzLoginTest(ctx context.Context, cmd *base.Command, args []string) error {
lg := logger.FromContext(ctx)
lg := cfg.Log

if err := cmd.Flag.Parse(args); err != nil {
base.SetExitStatus(base.SInvalidParameters)
Expand Down Expand Up @@ -95,9 +95,9 @@ func runEzLoginTest(ctx context.Context, cmd *base.Command, args []string) error
return err
}
if res.Err == nil {
lg.Println("OK")
lg.Info("OK")
} else {
lg.Println("ERROR")
lg.Error("ERROR", "error", *res.Err)
base.SetExitStatus(base.SApplicationError)
return errors.New(*res.Err)
}
Expand Down
Loading

0 comments on commit 2fc218d

Please sign in to comment.