~gloatingfiddle/coffeebeans

837d1d99784b68c24ef17ed62cf9547ee392b3e7 — David Hagerty 30 days ago 2fca417
feat: logger with build info and environment info
1 files changed, 15 insertions(+), 5 deletions(-)

M internal/server/server.go
M internal/server/server.go => internal/server/server.go +15 -5
@@ 10,6 10,8 @@ import (
	"net/http"
	"sync"
	"time"

	"git.sr.ht/~gloatingfiddle/coffeebeans/internal/version"
)

var logLevel = new(slog.LevelVar)


@@ 20,6 22,14 @@ type env struct {

func Run(ctx context.Context, baseCancel context.CancelFunc, args []string, stdout, stderr io.Writer) int {
	e := fromArgs(args)

	logger := slog.New(slog.NewJSONHandler(stdout, &slog.HandlerOptions{
		AddSource: logLevel.Level() == slog.LevelDebug,
		Level:     logLevel,
	})).With(slog.Group("build", slog.String("version", version.Revision), slog.Bool("dirty", version.DirtyTree), slog.Time("date", version.LastCommitDate)))

	logger.InfoContext(ctx, "starting", slog.Group("environment", slog.Int("port", e.port)))

	mux := http.NewServeMux()
	mux.Handle("/{$}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello world!"))


@@ 30,8 40,8 @@ func Run(ctx context.Context, baseCancel context.CancelFunc, args []string, stdo
	}
	go func() {
		if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			slog.ErrorContext(ctx, "listening", "error", err)
			slog.InfoContext(ctx, "canceling base context")
			logger.ErrorContext(ctx, "listening", "error", err)
			logger.InfoContext(ctx, "canceling base context")
			baseCancel()
		}
	}()


@@ 41,13 51,13 @@ func Run(ctx context.Context, baseCancel context.CancelFunc, args []string, stdo
	go func() {
		defer wg.Done()
		<-ctx.Done()
		slog.InfoContext(ctx, "base context cancelled", "error", ctx.Err())
		logger.InfoContext(ctx, "base context cancelled", "error", ctx.Err())
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		slog.InfoContext(ctx, "shutting down server")
		logger.InfoContext(ctx, "shutting down server")
		err := s.Shutdown(shutdownCtx)
		if err != nil {
			slog.ErrorContext(ctx, "server shutdown failed", "error", err)
			logger.ErrorContext(ctx, "server shutdown failed", "error", err)
		}
	}()
	wg.Wait()