Skip to content

Commit

Permalink
Change logger to log/slog (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
MicahParks authored Sep 10, 2023
1 parent f364bca commit 3df8475
Show file tree
Hide file tree
Showing 486 changed files with 54,196 additions and 51,644 deletions.
5 changes: 3 additions & 2 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 5,8 @@ import (
"crypto/ed25519"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
Expand All @@ -17,7 19,6 @@ import (
"github.com/MicahParks/keyfunc"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"go.uber.org/zap"

mld "github.com/MicahParks/magiclinksdev"
"github.com/MicahParks/magiclinksdev/config"
Expand Down Expand Up @@ -370,7 371,7 @@ func newClient(ctx context.Context, t *testing.T) Client {
HTTPMux: nil,
MagicLinkErrorHandler: nil,
MiddlewareHook: nil,
Sugared: zap.NewNop().Sugar(),
Logger: slog.New(slog.NewJSONHandler(io.Discard, nil)),
}
conf, err := conf.DefaultsAndValidate()
if err != nil {
Expand Down
26 changes: 10 additions & 16 deletions cmd/migrate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 6,6 @@ import (
"os"

jt "github.com/MicahParks/jsontype"
"go.uber.org/zap"

mld "github.com/MicahParks/magiclinksdev"
"github.com/MicahParks/magiclinksdev/setup"
Expand All @@ -22,45 21,40 @@ func main() {
log.Fatalf(mld.LogFmt, "Failed to read configuration.", err)
}

var logger *zap.Logger
if os.Getenv("DEV_MODE") == "true" {
logger, err = zap.NewDevelopment()
} else {
logger, err = zap.NewProduction()
}
if err != nil {
log.Fatalf(mld.LogFmt, "Failed to create logger.", err)
}
sugared := logger.Sugar()
logger := setup.CreateLogger(conf.Server)

_, pool, err := postgres.New(ctx, conf.Storage)
if err != nil {
sugared.Fatalw("Failed to create postgres pool.",
logger.ErrorContext(ctx, "Failed to create postgres pool.",
mld.LogErr, err,
)
os.Exit(1)
}

k, err := postgres.DecodeAES256Base64(conf.Storage.AES256KeyBase64)
if err != nil {
sugared.Fatalw("Failed to decode AES256 key.",
logger.ErrorContext(ctx, "Failed to decode AES256 key.",
mld.LogErr, err,
)
os.Exit(1)
}
options := postgres.MigratorOptions{
EncryptionKey: k,
Sugared: sugared,
Logger: logger,
}
migrator, err := postgres.NewMigrator(pool, options)
if err != nil {
sugared.Fatalw("Failed to create migrator.",
logger.ErrorContext(ctx, "Failed to create migrator.",
mld.LogErr, err,
)
os.Exit(1)
}

err = migrator.Migrate(ctx)
if err != nil {
sugared.Fatalw("Failed to migrate.",
logger.ErrorContext(ctx, "Failed to migrate.",
mld.LogErr, err,
)
os.Exit(1)
}
}
86 changes: 6 additions & 80 deletions cmd/multi_provider/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 2,12 @@ package main

import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"

jt "github.com/MicahParks/jsontype"
"go.uber.org/zap"

mld "github.com/MicahParks/magiclinksdev"
"github.com/MicahParks/magiclinksdev/config"
"github.com/MicahParks/magiclinksdev/network"
"github.com/MicahParks/magiclinksdev/setup"
)

Expand All @@ -28,86 20,20 @@ func main() {
log.Fatalf(mld.LogFmt, "Failed to read configuration.", err)
}

var logger *zap.Logger
if os.Getenv("DEV_MODE") == "true" {
logger, err = zap.NewDevelopment()
} else {
logger, err = zap.NewProduction()
}
if err != nil {
log.Fatalf(mld.LogFmt, "Failed to create logger.", err)
}
logger.Info("Starting server...")
sugared := logger.Sugar()
logger := setup.CreateLogger(conf.Server)
logger.InfoContext(ctx, "Starting server...")

options := setup.ServerOptions{
Sugared: sugared,
Logger: logger,
}

server, err := setup.CreateMultiProviderServer(ctx, conf, options)
if err != nil {
sugared.Fatalw("Failed to setup server.",
mld.LogErr, err,
)
}

port := os.Getenv("PORT")
if port == "" {
port = "8080"
}

mux, err := network.CreateHTTPHandlers(server)
if err != nil {
sugared.Fatalw("Failed to create HTTP handlers.",
mld.LogErr, err,
)
}
httpServer := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: mux,
}

idleConnsClosed := make(chan struct{})
go serverShutdown(ctx, conf.Server, sugared, idleConnsClosed, httpServer)

sugared.Infow("Server is listening.",
"port", port,
)
err = httpServer.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
sugared.Fatalw("Failed to listen and serve.",
mld.LogErr, err,
)
}

<-idleConnsClosed
}

func serverShutdown(ctx context.Context, conf config.Config, sugared *zap.SugaredLogger, idleConnsClosed chan struct{}, srv *http.Server) {
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
select {
case <-shutdown:
sugared.Info("Got a SIGINT or SIGTERM.")
case <-ctx.Done():
sugared.Infow("Context over.",
mld.LogErr, ctx.Err(),
)
}

err := sugared.Sync()
if err != nil {
log.Printf(mld.LogFmt, "Failed to sync logger on server shutdown.", err)
}

shutdownCtx, cancel := context.WithTimeout(context.Background(), conf.ShutdownTimeout.Get())
defer cancel()
err = srv.Shutdown(shutdownCtx)
if err != nil {
sugared.Infow("Couldn't shut down server before time ended.",
logger.ErrorContext(ctx, "Failed to setup server.",
mld.LogErr, err,
)
os.Exit(1)
}

close(idleConnsClosed)
setup.RunServer(ctx, logger, server)
}
86 changes: 6 additions & 80 deletions cmd/nop_provider/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 2,12 @@ package main

import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"

jt "github.com/MicahParks/jsontype"
"go.uber.org/zap"

mld "github.com/MicahParks/magiclinksdev"
"github.com/MicahParks/magiclinksdev/config"
"github.com/MicahParks/magiclinksdev/network"
"github.com/MicahParks/magiclinksdev/setup"
)

Expand All @@ -28,86 20,20 @@ func main() {
log.Fatalf(mld.LogFmt, "Failed to read configuration.", err)
}

var logger *zap.Logger
if os.Getenv("DEV_MODE") == "true" {
logger, err = zap.NewDevelopment()
} else {
logger, err = zap.NewProduction()
}
if err != nil {
log.Fatalf(mld.LogFmt, "Failed to create logger.", err)
}
logger.Info("Starting server...")
sugared := logger.Sugar()
logger := setup.CreateLogger(conf.Server)
logger.InfoContext(ctx, "Starting server...")

options := setup.ServerOptions{
Sugared: sugared,
Logger: logger,
}

server, err := setup.CreateNopProviderServer(ctx, conf, options)
if err != nil {
sugared.Fatalw("Failed to setup server.",
mld.LogErr, err,
)
}

port := os.Getenv("PORT")
if port == "" {
port = "8080"
}

mux, err := network.CreateHTTPHandlers(server)
if err != nil {
sugared.Fatalw("Failed to create HTTP handlers.",
mld.LogErr, err,
)
}
httpServer := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: mux,
}

idleConnsClosed := make(chan struct{})
go serverShutdown(ctx, conf.Server, sugared, idleConnsClosed, httpServer)

sugared.Infow("Server is listening.",
"port", port,
)
err = httpServer.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
sugared.Fatalw("Failed to listen and serve.",
mld.LogErr, err,
)
}

<-idleConnsClosed
}

func serverShutdown(ctx context.Context, conf config.Config, sugared *zap.SugaredLogger, idleConnsClosed chan struct{}, srv *http.Server) {
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
select {
case <-shutdown:
sugared.Info("Got a SIGINT or SIGTERM.")
case <-ctx.Done():
sugared.Infow("Context over.",
mld.LogErr, ctx.Err(),
)
}

err := sugared.Sync()
if err != nil {
log.Printf(mld.LogFmt, "Failed to sync logger on server shutdown.", err)
}

shutdownCtx, cancel := context.WithTimeout(context.Background(), conf.ShutdownTimeout.Get())
defer cancel()
err = srv.Shutdown(shutdownCtx)
if err != nil {
sugared.Infow("Couldn't shut down server before time ended.",
logger.ErrorContext(ctx, "Failed to setup server.",
mld.LogErr, err,
)
os.Exit(1)
}

close(idleConnsClosed)
setup.RunServer(ctx, logger, server)
}
Loading

0 comments on commit 3df8475

Please sign in to comment.