Skip to content

Commit

Permalink
feat: use log/slog for logging (with logrus backend)
Browse files Browse the repository at this point in the history
  • Loading branch information
szkiba committed Jun 28, 2024
1 parent b701dcb commit e304f84
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 40 deletions.
5 changes: 3 additions & 2 deletions build.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -54,7 +55,7 @@ func build(ctx context.Context, deps k6deps.Dependencies, opts *Options) (*url.U
}

func newBuildService(ctx context.Context, opts *Options) (k6build.BuildService, error) {
if opts.BuildServiceURL != nil {
if opts != nil && opts.BuildServiceURL != nil {
return newBuildServiceClient(opts)
}

Expand Down Expand Up @@ -88,7 +89,7 @@ func newLocalBuildService(ctx context.Context, opts *Options) (k6build.BuildServ
Catalog: catfile,
CopyGoEnv: true,
CacheDir: filepath.Join(cachedir, "build"),
Verbose: opts.verbose(),
Verbose: slog.Default().Enabled(ctx, slog.LevelDebug),
}

return k6build.NewLocalBuildService(ctx, conf)
Expand Down
37 changes: 25 additions & 12 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package cmd
import (
"context"
_ "embed"
"log/slog"
"net/url"
"os"

Expand All @@ -19,6 +20,8 @@ type options struct {
k6exec.Options
buildServiceURL string
extensionCatalogURL string
verbose bool
levelVar *slog.LevelVar
}

func (o *options) postProcess() error {
Expand All @@ -40,6 +43,10 @@ func (o *options) postProcess() error {
o.ExtensionCatalogURL = val
}

if o.verbose && o.levelVar != nil {
o.levelVar.Set(slog.LevelDebug)
}

return nil
}

Expand All @@ -55,8 +62,8 @@ func (o *options) init() {
}

// New creates new cobra command for exec command.
func New() *cobra.Command {
opts := new(options)
func New(levelVar *slog.LevelVar) *cobra.Command {
opts := &options{levelVar: levelVar}

opts.init()

Expand All @@ -72,7 +79,9 @@ func New() *cobra.Command {
PersistentPreRunE: func(_ *cobra.Command, _ []string) error { return opts.postProcess() },
}

root.AddCommand(subcommands(&opts.Options)...)
root.SetVersionTemplate(`{{with .Name}}{{printf "%s " .}}{{end}}{{printf "%s\n" .Version}}`)

root.AddCommand(subcommands(opts)...)

flags := root.PersistentFlags()

Expand All @@ -89,7 +98,7 @@ func New() *cobra.Command {
"URL of the k6 build service to be used",
)
flags.BoolVarP(
&opts.Verbose,
&opts.verbose,
"verbose",
"v",
false,
Expand All @@ -102,13 +111,13 @@ func New() *cobra.Command {
}

func usage(cmd *cobra.Command, args []string) {
err := exec(cmd, append(args, "-h"), nil)
err := exec(cmd, append(args, "-h"), new(options))
if err != nil {
cmd.PrintErr(err)
}
}

func exec(sub *cobra.Command, args []string, opts *k6exec.Options) error {
func exec(sub *cobra.Command, args []string, opts *options) error {
var (
deps k6deps.Dependencies
err error
Expand All @@ -119,16 +128,20 @@ func exec(sub *cobra.Command, args []string, opts *k6exec.Options) error {
dopts.Script.Name = scriptname
}

dopts.Manifest.Name = "package.json"

deps, err = k6deps.Analyze(&dopts)
if err != nil {
return err
}

args = append([]string{sub.Name()}, args...)
cmdargs := []string{sub.Name()}

if opts.verbose {
cmdargs = append(cmdargs, "-v")
}

cmdargs = append(cmdargs, args...)

cmd, err := k6exec.Command(context.Background(), args, deps, opts)
cmd, err := k6exec.Command(context.Background(), cmdargs, deps, &opts.Options)
if err != nil {
return err
}
Expand All @@ -137,7 +150,7 @@ func exec(sub *cobra.Command, args []string, opts *k6exec.Options) error {
cmd.Stdout = os.Stdout //nolint:forbidigo
cmd.Stdin = os.Stdin //nolint:forbidigo

defer k6exec.CleanupState(opts) //nolint:errcheck
defer k6exec.CleanupState(&opts.Options) //nolint:errcheck

return cmd.Run()
}
Expand All @@ -163,7 +176,7 @@ func scriptArg(cmd *cobra.Command, args []string) (string, bool) {
return last, true
}

func subcommands(opts *k6exec.Options) []*cobra.Command {
func subcommands(opts *options) []*cobra.Command {
annext := map[string]string{useExtensions: "true"}

all := make([]*cobra.Command, 0, len(commands))
Expand Down
10 changes: 1 addition & 9 deletions cmd/k6exec/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package main
import (
"errors"
"os"
"strings"

"github.com/evanw/esbuild/pkg/api"
"golang.org/x/term"
)

Expand All @@ -22,13 +20,7 @@ func formatError(err error) string {
return perr.Format(width, color)
}

return strings.Join(
api.FormatMessages(
[]api.Message{{Text: err.Error()}},
api.FormatMessagesOptions{TerminalWidth: width, Color: color},
),
"\n",
)
return err.Error()
}

func formatOptions(fd int) (int, bool) {
Expand Down
30 changes: 22 additions & 8 deletions cmd/k6exec/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
package main

import (
"log"
"log/slog"
"os"
"strings"

"github.com/grafana/k6exec/cmd"
sloglogrus "github.com/samber/slog-logrus/v2"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand All @@ -16,12 +18,26 @@ var (
version = "dev"
)

func initLogging() *slog.LevelVar {
var levelVar = new(slog.LevelVar)

logrus.SetLevel(logrus.DebugLevel)

logger := slog.New(sloglogrus.Option{Level: levelVar}.NewLogrusHandler())
logger = logger.With("app", appname)

slog.SetDefault(logger)

return levelVar
}

func main() {
runCmd(newCmd(os.Args[1:])) //nolint:forbidigo
levelVar := initLogging()
runCmd(newCmd(os.Args[1:], levelVar)) //nolint:forbidigo
}

func newCmd(args []string) *cobra.Command {
cmd := cmd.New()
func newCmd(args []string, levelVar *slog.LevelVar) *cobra.Command {
cmd := cmd.New(levelVar)
cmd.Use = strings.Replace(cmd.Use, cmd.Name(), appname, 1)
cmd.Version = version
cmd.SetArgs(args)
Expand All @@ -30,10 +46,8 @@ func newCmd(args []string) *cobra.Command {
}

func runCmd(cmd *cobra.Command) {
log.SetFlags(0)
log.Writer()

if err := cmd.Execute(); err != nil {
log.Fatal(formatError(err))
slog.Error(formatError(err))
os.Exit(1) //nolint:forbidigo
}
}
8 changes: 6 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,30 @@ toolchain go1.22.4

require (
github.com/adrg/xdg v0.4.0
github.com/evanw/esbuild v0.21.5
github.com/grafana/clireadme v0.1.0
github.com/grafana/k6build v0.2.0
github.com/grafana/k6deps v0.1.2-0.20240617140502-f1b0dfc93f7f
github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79
github.com/samber/slog-logrus/v2 v2.3.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.8.1
golang.org/x/term v0.21.0
)

require (
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/evanw/esbuild v0.21.5 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/grafana/k6catalog v0.1.0 // indirect
github.com/grafana/k6foundry v0.1.3 // indirect
github.com/grafana/k6pack v0.2.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/samber/lo v1.38.1 // indirect
github.com/samber/slog-common v0.16.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect
golang.org/x/mod v0.18.0 // indirect
golang.org/x/sys v0.21.0 // indirect
)
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/samber/slog-common v0.16.0 h1:2/t1EcFd1Ru77mh2ab+8B6NBHnEXsBBHtOJc7PSH0aI=
github.com/samber/slog-common v0.16.0/go.mod h1:Qjrfhwk79XiCIhBj8+jTq1Cr0u9rlWbjawh3dWXzaHk=
github.com/samber/slog-logrus/v2 v2.3.0 h1:aRQY593/b1SgePwa5EwpNEGgFV/lczMse/fjmCsucOE=
github.com/samber/slog-logrus/v2 v2.3.0/go.mod h1:GTMrL8UxGKhzLMjJLIhhTaLIXmLF51tsEHEq1tsJJ7I=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
Expand All @@ -45,6 +51,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0=
golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
6 changes: 0 additions & 6 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ type Options struct {
// ExtensionCatalogURL contains the URL of the k6 extension catalog to be used.
// If absent, DefaultExtensionCatalogURL will be used.
ExtensionCatalogURL *url.URL
// Verbose flag enables verbose logging.
Verbose bool
// BuildServiceURL contains the URL of the k6 build service to be used.
// If the value is not nil, the k6 binary is built using the build service instead of the local build.
BuildServiceURL *url.URL
Expand Down Expand Up @@ -140,7 +138,3 @@ func (o *Options) stateSubdir() (string, error) {

return dir, nil
}

func (o *Options) verbose() bool {
return o != nil && o.Verbose
}
2 changes: 1 addition & 1 deletion tools/gendoc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func main() {
root := cmd.New()
root := cmd.New(nil)
root.Use = strings.ReplaceAll(root.Use, "exec", "k6exec")
clireadme.Main(root, 1)
}

0 comments on commit e304f84

Please sign in to comment.