Skip to content
This repository has been archived by the owner on Jul 18, 2023. It is now read-only.

Commit

Permalink
feat: add simplejson.WithLogger() to pass a specific slog Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
clambin committed Jan 11, 2023
1 parent 3837ac8 commit c5ea305
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
10 changes: 10 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package simplejson

import (
"github.com/clambin/go-common/httpserver/middleware"
"golang.org/x/exp/slog"
)

// Option specified configuration options for Server
Expand Down Expand Up @@ -29,3 +30,12 @@ type WithHTTPMetrics struct {
func (o WithHTTPMetrics) apply(s *Server) {
s.prometheusMetrics = middleware.NewPrometheusMetrics(o.Option)
}

// WithLogger configures the router to use the provided slog Logger for logging. If no logger is provided, slog.Default() is used instead.
type WithLogger struct {
Logger *slog.Logger
}

func (o WithLogger) apply(s *Server) {
s.logger = o.Logger
}
4 changes: 3 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Server struct {
Handlers map[string]Handler
prometheusMetrics *middleware.PrometheusMetrics
queryMetrics *QueryMetrics
logger *slog.Logger
}

var _ prometheus.Collector = &Server{}
Expand All @@ -25,14 +26,15 @@ func New(handlers map[string]Handler, options ...Option) *Server {
s := Server{
Handlers: handlers,
Router: chi.NewRouter(),
logger: slog.Default(),
}
for _, o := range options {
o.apply(&s)
}

s.Router.Use(middleware2.Heartbeat("/"))
s.Router.Group(func(r chi.Router) {
r.Use(middleware.Logger(slog.Default()))
r.Use(middleware.Logger(s.logger))
if s.prometheusMetrics != nil {
r.Use(s.prometheusMetrics.Handle)
}
Expand Down
7 changes: 6 additions & 1 deletion server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,21 @@ import (
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/exp/slog"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
)

var update = flag.Bool("update", false, "update .golden files")

func TestNewRouter(t *testing.T) {
r := simplejson.New(nil)
logger := slog.New(slog.NewJSONHandler(os.Stdout).WithAttrs([]slog.Attr{
slog.String("module", "simplejson"),
}))
r := simplejson.New(nil, simplejson.WithLogger{Logger: logger})

for _, path := range []string{"/"} {
w := httptest.NewRecorder()
Expand Down

0 comments on commit c5ea305

Please sign in to comment.