Skip to content

Commit

Permalink
Merge pull request #353 from uselagoon/slog
Browse files Browse the repository at this point in the history
feat: use slog instead of zap for structured logging
  • Loading branch information
smlx authored Jan 16, 2024
2 parents b909503 + 221ceef commit 321a508
Show file tree
Hide file tree
Showing 19 changed files with 243 additions and 352 deletions.
14 changes: 8 additions & 6 deletions cmd/ssh-portal-api/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// Package main is the executable ssh-portal-api service.
// Package main implements the ssh-portal-api service.
package main

import (
"log/slog"
"os"

"github.com/alecthomas/kong"
"go.uber.org/zap"
)

// CLI represents the command-line interface.
Expand All @@ -20,13 +22,13 @@ func main() {
kong.UsageOnError(),
)
// init logger
var log *zap.Logger
var log *slog.Logger
if cli.Debug {
log = zap.Must(zap.NewDevelopment(zap.AddStacktrace(zap.ErrorLevel)))
log = slog.New(slog.NewJSONHandler(os.Stderr,
&slog.HandlerOptions{Level: slog.LevelDebug}))
} else {
log = zap.Must(zap.NewProduction())
log = slog.New(slog.NewJSONHandler(os.Stderr, nil))
}
defer log.Sync() //nolint:errcheck
// execute CLI
kctx.FatalIfErrorf(kctx.Run(log))
}
4 changes: 2 additions & 2 deletions cmd/ssh-portal-api/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"log/slog"
"os/signal"
"syscall"

Expand All @@ -12,7 +13,6 @@ import (
"github.com/uselagoon/ssh-portal/internal/metrics"
"github.com/uselagoon/ssh-portal/internal/rbac"
"github.com/uselagoon/ssh-portal/internal/sshportalapi"
"go.uber.org/zap"
)

// ServeCmd represents the serve command.
Expand All @@ -29,7 +29,7 @@ type ServeCmd struct {
}

// Run the serve command to ssh-portal API requests.
func (cmd *ServeCmd) Run(log *zap.Logger) error {
func (cmd *ServeCmd) Run(log *slog.Logger) error {
// metrics needs a separate context because deferred Shutdown() will exit
// immediately the context is done, which is the case for ctx on SIGTERM.
m := metrics.NewServer(log, ":9911")
Expand Down
14 changes: 8 additions & 6 deletions cmd/ssh-portal/main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// Package main implements the ssh-portal executable.
// Package main implements the ssh-portal service.
package main

import (
"log/slog"
"os"

"github.com/alecthomas/kong"
"github.com/moby/spdystream"
"go.uber.org/zap"
)

// CLI represents the command-line interface.
Expand All @@ -23,13 +25,13 @@ func main() {
kong.UsageOnError(),
)
// init logger
var log *zap.Logger
var log *slog.Logger
if cli.Debug {
log = zap.Must(zap.NewDevelopment(zap.AddStacktrace(zap.ErrorLevel)))
log = slog.New(slog.NewJSONHandler(os.Stderr,
&slog.HandlerOptions{Level: slog.LevelDebug}))
} else {
log = zap.Must(zap.NewProduction())
log = slog.New(slog.NewJSONHandler(os.Stderr, nil))
}
defer log.Sync() //nolint:errcheck
// execute CLI
kctx.FatalIfErrorf(kctx.Run(log))
}
8 changes: 4 additions & 4 deletions cmd/ssh-portal/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"log/slog"
"net"
"os/signal"
"syscall"
Expand All @@ -11,7 +12,6 @@ import (
"github.com/uselagoon/ssh-portal/internal/k8s"
"github.com/uselagoon/ssh-portal/internal/metrics"
"github.com/uselagoon/ssh-portal/internal/sshserver"
"go.uber.org/zap"
)

// ServeCmd represents the serve command.
Expand All @@ -25,7 +25,7 @@ type ServeCmd struct {
}

// Run the serve command to handle SSH connection requests.
func (cmd *ServeCmd) Run(log *zap.Logger) error {
func (cmd *ServeCmd) Run(log *slog.Logger) error {
// metrics needs a separate context because deferred Shutdown() will exit
// immediately the context is done, which is the case for ctx on SIGTERM.
m := metrics.NewServer(log, ":9912")
Expand All @@ -42,10 +42,10 @@ func (cmd *ServeCmd) Run(log *zap.Logger) error {
stop()
}),
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) {
log.Warn("nats disconnected", zap.Error(err))
log.Warn("nats disconnected", slog.Any("error", err))
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
log.Info("nats reconnected", zap.String("url", nc.ConnectedUrl()))
log.Info("nats reconnected", slog.String("url", nc.ConnectedUrl()))
}))
if err != nil {
return fmt.Errorf("couldn't connect to NATS server: %v", err)
Expand Down
14 changes: 8 additions & 6 deletions cmd/ssh-token/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// Package main is the executable ssh-token service.
// Package main implements the ssh-token service.
package main

import (
"log/slog"
"os"

"github.com/alecthomas/kong"
"go.uber.org/zap"
)

// CLI represents the command-line interface.
Expand All @@ -20,13 +22,13 @@ func main() {
kong.UsageOnError(),
)
// init logger
var log *zap.Logger
var log *slog.Logger
if cli.Debug {
log = zap.Must(zap.NewDevelopment(zap.AddStacktrace(zap.ErrorLevel)))
log = slog.New(slog.NewJSONHandler(os.Stderr,
&slog.HandlerOptions{Level: slog.LevelDebug}))
} else {
log = zap.Must(zap.NewProduction())
log = slog.New(slog.NewJSONHandler(os.Stderr, nil))
}
defer log.Sync() //nolint:errcheck
// execute CLI
kctx.FatalIfErrorf(kctx.Run(log))
}
4 changes: 2 additions & 2 deletions cmd/ssh-token/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"log/slog"
"net"
"os/signal"
"syscall"
Expand All @@ -13,7 +14,6 @@ import (
"github.com/uselagoon/ssh-portal/internal/metrics"
"github.com/uselagoon/ssh-portal/internal/rbac"
"github.com/uselagoon/ssh-portal/internal/sshtoken"
"go.uber.org/zap"
)

// ServeCmd represents the serve command.
Expand All @@ -35,7 +35,7 @@ type ServeCmd struct {
}

// Run the serve command to ssh-portal API requests.
func (cmd *ServeCmd) Run(log *zap.Logger) error {
func (cmd *ServeCmd) Run(log *slog.Logger) error {
// metrics needs a separate context because deferred Shutdown() will exit
// immediately the context is done, which is the case for ctx on SIGTERM.
m := metrics.NewServer(log, ":9948")
Expand Down
2 changes: 0 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ require (
github.com/prometheus/client_golang v1.18.0
github.com/zitadel/oidc/v3 v3.10.0
go.opentelemetry.io/otel v1.21.0
go.uber.org/zap v1.26.0
golang.org/x/crypto v0.18.0
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63
golang.org/x/oauth2 v0.16.0
Expand Down Expand Up @@ -68,7 +67,6 @@ require (
github.com/zitadel/schema v1.3.0 // indirect
go.opentelemetry.io/otel/metric v1.21.0 // indirect
go.opentelemetry.io/otel/trace v1.21.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/term v0.16.0 // indirect
Expand Down
6 changes: 0 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,6 @@ go.opentelemetry.io/otel/metric v1.21.0 h1:tlYWfeo+Bocx5kLEloTjbcDwBuELRrIFxwdQ3
go.opentelemetry.io/otel/metric v1.21.0/go.mod h1:o1p3CA8nNHW8j5yuQLdc1eeqEaPfzug24uvsyIEJRWM=
go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc=
go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ=
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
Expand Down
7 changes: 3 additions & 4 deletions internal/keycloak/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ package keycloak
import (
"context"
"fmt"
"log/slog"
"net/http"
"net/url"
"path"
"time"

"go.uber.org/zap"

"github.com/MicahParks/keyfunc/v2"
oidcClient "github.com/zitadel/oidc/v3/pkg/client"
"github.com/zitadel/oidc/v3/pkg/oidc"
Expand All @@ -24,12 +23,12 @@ type Client struct {
clientID string
clientSecret string
jwks *keyfunc.JWKS
log *zap.Logger
log *slog.Logger
oidcConfig *oidc.DiscoveryConfiguration
}

// NewClient creates a new keycloak client for the lagoon realm.
func NewClient(ctx context.Context, log *zap.Logger, keycloakURL, clientID,
func NewClient(ctx context.Context, log *slog.Logger, keycloakURL, clientID,
clientSecret string) (*Client, error) {
// discover OIDC config
issuerURL, err := url.Parse(keycloakURL)
Expand Down
4 changes: 2 additions & 2 deletions internal/keycloak/jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
Expand All @@ -14,7 +15,6 @@ import (
"github.com/alecthomas/assert/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/uselagoon/ssh-portal/internal/keycloak"
"go.uber.org/zap"
"golang.org/x/oauth2"
)

Expand Down Expand Up @@ -135,7 +135,7 @@ func TestUnmarshalLagoonClaims(t *testing.T) {

func TestValidateTokenClaims(t *testing.T) {
// set up logger
log := zap.Must(zap.NewDevelopment())
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
// set up test cases
validClaims := keycloak.LagoonClaims{
AuthorizedParty: "auth-server",
Expand Down
7 changes: 4 additions & 3 deletions internal/metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
// Package metrics implements the prometheus metrics server.
package metrics

import (
"log/slog"
"net/http"
"time"

"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
)

// NewServer returns a *http.Server serving prometheus metrics in a new
// goroutine.
// Caller should defer Shutdown() for cleanup.
func NewServer(log *zap.Logger, addr string) *http.Server {
func NewServer(log *slog.Logger, addr string) *http.Server {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
s := http.Server{
Expand All @@ -22,7 +23,7 @@ func NewServer(log *zap.Logger, addr string) *http.Server {
}
go func() {
if err := s.ListenAndServe(); err != http.ErrServerClosed {
log.Error("metrics server did not shut down cleanly", zap.Error(err))
log.Error("metrics server did not shut down cleanly", slog.Any("error", err))
}
}()
return &s
Expand Down
10 changes: 5 additions & 5 deletions internal/sshportalapi/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ package sshportalapi
import (
"context"
"fmt"
"log/slog"
"sync"

"github.com/google/uuid"
"github.com/nats-io/nats.go"
"github.com/uselagoon/ssh-portal/internal/lagoondb"
"github.com/uselagoon/ssh-portal/internal/rbac"
"go.uber.org/zap"
)

const (
Expand All @@ -31,7 +31,7 @@ type KeycloakService interface {
}

// ServeNATS sshportalapi NATS requests.
func ServeNATS(ctx context.Context, stop context.CancelFunc, log *zap.Logger,
func ServeNATS(ctx context.Context, stop context.CancelFunc, log *slog.Logger,
p *rbac.Permission, l LagoonDBService, k KeycloakService, natsURL string) error {
// setup synchronisation
wg := sync.WaitGroup{}
Expand All @@ -46,10 +46,10 @@ func ServeNATS(ctx context.Context, stop context.CancelFunc, log *zap.Logger,
wg.Done()
}),
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) {
log.Warn("nats disconnected", zap.Error(err))
log.Warn("nats disconnected", slog.Any("error", err))
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
log.Info("nats reconnected", zap.String("url", nc.ConnectedUrl()))
log.Info("nats reconnected", slog.String("url", nc.ConnectedUrl()))
}))
if err != nil {
return fmt.Errorf("couldn't connect to NATS server: %v", err)
Expand All @@ -69,7 +69,7 @@ func ServeNATS(ctx context.Context, stop context.CancelFunc, log *zap.Logger,
<-ctx.Done()
// drain and log errors
if err := nc.Drain(); err != nil {
log.Warn("couldn't drain connection", zap.Error(err))
log.Warn("couldn't drain connection", slog.Any("error", err))
}
// wait for connection to close
wg.Wait()
Expand Down
Loading

0 comments on commit 321a508

Please sign in to comment.