Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for structured logging #183

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions client/session/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package session

import (
"context"
"log"
"log/slog"
"os"
)

// Session is an abstraction around session creation based on credentials from
Expand All @@ -16,7 +17,8 @@ type Session interface {
// Must provides a helper that either creates a Session or dies trying.
func Must(out Session, err error) Session {
if err != nil {
log.Fatalf("Could not create a Spacelift session: %v", err)
slog.Error("Could not create a Spacelift session", "err", err)
os.Exit(1)
}

return out
Expand Down
8 changes: 5 additions & 3 deletions internal/cmd/module/local_preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@ package module
import (
"context"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"sync"
"time"

"golang.org/x/sync/errgroup"

"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/mholt/archiver/v3"
"github.com/shurcooL/graphql"
"github.com/urfave/cli/v2"
"golang.org/x/sync/errgroup"

"github.com/spacelift-io/spacectl/internal"
"github.com/spacelift-io/spacectl/internal/cmd/authenticated"
Expand Down Expand Up @@ -131,7 +132,8 @@ func localPreview() cli.ActionFunc {
})
}
if err := g.Wait(); err != nil {
log.Fatal("couldn't get runs: ", err)
slog.Error("couldn't get runs", "err", err)
os.Exit(1)
}
model.setRuns(newRuns)
}
Expand Down
13 changes: 8 additions & 5 deletions internal/cmd/profile/login_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"context"
"encoding/base64"
"fmt"
"log"
"log/slog"
"net"
"net/http"
"net/url"
Expand All @@ -14,11 +14,12 @@ import (
"syscall"
"time"

"golang.org/x/term"

"github.com/manifoldco/promptui"
"github.com/pkg/browser"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"golang.org/x/term"

"github.com/spacelift-io/spacectl/client/session"
"github.com/spacelift-io/spacectl/internal"
Expand Down Expand Up @@ -226,11 +227,12 @@ func loginUsingWebBrowser(ctx *cli.Context, creds *session.StoredCredentials) er

infoPage, err := url.Parse(creds.Endpoint)
if err != nil {
log.Fatal(err)
slog.Error("Error parsing URL", "err", err)
os.Exit(1)
}

if handlerErr != nil {
log.Println(handlerErr)
slog.Error("login error", "err", handlerErr)
infoPage.Path = cliAuthFailurePage
http.Redirect(w, r, infoPage.String(), http.StatusTemporaryRedirect)
} else {
Expand Down Expand Up @@ -320,7 +322,8 @@ func serveOnOpenPort(host *string, port *int, handler func(w http.ResponseWriter
go func() {
if err := server.Serve(l); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("could not start local server: %s", err)
slog.Error("could not start local server", "err", err)
os.Exit(1)
}
}
}()
Expand Down
59 changes: 56 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"log"
"log/slog"
"os"
"time"

Expand All @@ -19,11 +19,15 @@ import (

var version = "dev"
var date = "2006-01-02T15:04:05Z"
var loggingLevel = new(slog.LevelVar)

func main() {

compileTime, err := time.Parse(time.RFC3339, date)

if err != nil {
log.Fatalf("Could not parse compilation date: %v", err)
slog.Error("Could not parse compilation date", "err", err)
os.Exit(1)
}
app := &cli.App{
Name: "spacectl",
Expand All @@ -40,9 +44,58 @@ func main() {
versioncmd.Command(version),
workerpools.Command(),
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "log-format",
Aliases: []string{"f"},
Usage: "Log format: json, text",
Value: "text",
},
&cli.StringFlag{
Name: "log-level",
Aliases: []string{"l"},
Usage: "Log level: debug, info, warn, error",
Value: "info",
},
},
Before: func(c *cli.Context) error {
var logger *slog.Logger
switch c.String("log-format") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: It's kinda nicer when flags are defined vars as we can later use those to extract values from context: https://github.com/spacelift-io/spacectl/blob/main/internal/cmd/module/create_version.go#L13

You could just define them above main here 🤷🏻

case "json":
logger = slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: loggingLevel,
}))
case "text":
logger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: loggingLevel,
}))
default:
return cli.Exit("Invalid log format", 1)
}

switch c.String("log-level") {
case "debug":
loggingLevel.Set(slog.LevelDebug)
case "info":
loggingLevel.Set(slog.LevelInfo)
case "warn":
loggingLevel.Set(slog.LevelWarn)
case "error":
loggingLevel.Set(slog.LevelError)
default:
return cli.Exit("Invalid log level", 1)
}

slog.SetDefault(logger)

return nil
},
}

if err := app.Run(os.Args); err != nil {
log.Fatal(err)
slog.Error("error", "err", err)
os.Exit(1)
}
}