Skip to content

Commit

Permalink
maj: better logging via slog defer
Browse files Browse the repository at this point in the history
  • Loading branch information
burgesQ committed Sep 13, 2023
1 parent cff0f78 commit 46ab52a
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 39 deletions.
6 changes: 3 additions & 3 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (c *icontext) FetchContent(dest interface{}) ErrorHandled {
b := c.PostBody()

if e := json.Unmarshal(b, &dest); e != nil {
c.slog.Error("fetching payload", "error", e)
c.slog.Error("fetching payload", slog.Any("error", e))

return errUnprocessablePayload
}
Expand All @@ -136,7 +136,7 @@ func (c *icontext) FetchContent(dest interface{}) ErrorHandled {
// this implemtation use validator to anotate & check struct
func (c *icontext) Validate(dest interface{}) ErrorHandled {
if e := validate.Struct(dest); e != nil {
c.slog.Error("validating form or query param", "error", e)
c.slog.Error("validating form or query param", slog.Any("error", e))

var ev validator.ValidationErrors

Expand Down Expand Up @@ -172,7 +172,7 @@ func (c *icontext) DecodeQP(dest interface{}) ErrorHandled {
})

if e := decoder.Decode(dest, m); e != nil {
c.slog.Error("validating query params", "error", e)
c.slog.Error("validating query params", slog.Any("error", e))

return NewUnprocessable(NewErrorFromError(e))
}
Expand Down
8 changes: 6 additions & 2 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ func handleNotFound(c Context) error {
fc := c.GetFastContext()

c.GetStructuredLogger().Info("[!] 404 reached", slog.Group("request",
"ip", GetIPFromRequest(fc), "method", fc.Method(), "uri", fc.RequestURI()))
slog.String("ip", GetIPFromRequest(fc)),
slog.String("method", string(fc.Method())),
slog.String("uri", string(fc.RequestURI()))))

return c.JSONNotFound(json.RawMessage(`{"status":404,"message":"not found"}`))
}
Expand All @@ -82,7 +84,9 @@ func handleNotAllowed(c Context) error {
fc := c.GetFastContext()

c.GetStructuredLogger().Info("[!] 405 reached", slog.Group("request",
"ip", GetIPFromRequest(fc), "method", fc.Method(), "uri", fc.RequestURI()))
slog.String("ip", GetIPFromRequest(fc)),
slog.String("method", string(fc.Method())),
slog.String("uri", string(fc.RequestURI()))))

return c.JSONMethodNotAllowed(json.RawMessage(`{"status":405,"message":"method not allowed"}`))
}
4 changes: 3 additions & 1 deletion response.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package webfmwk

import "log/slog"

type (
// Header represent a header in a string key:value form.
Header [2]string
Expand Down Expand Up @@ -55,7 +57,7 @@ func (c *icontext) setHeaders(headers ...Header) {
for _, h := range headers {
key, val := h[0], h[1]
if key == "" || val == "" {
c.slog.Warn("can't set header: empty value", "key", key, "val", val)
c.slog.Warn("can't set header: empty value", slog.String("key", key), slog.String("val", val))

return
}
Expand Down
3 changes: 2 additions & 1 deletion response_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package webfmwk
import (
"bytes"
"fmt"
"log/slog"
"net/http"

"github.com/segmentio/encoding/json"
Expand Down Expand Up @@ -76,7 +77,7 @@ func (c *icontext) JSONBlob(statusCode int, content []byte) error {
)

if e := run(); e != nil {
c.slog.Error("cannot prettying the content", "error", e)
c.slog.Error("cannot prettying the content", slog.Any("error", e))
} else {
content = out.Bytes()
}
Expand Down
11 changes: 7 additions & 4 deletions route.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package webfmwk

import (
"context"
"log/slog"

"github.com/fasthttp/router"
"github.com/segmentio/encoding/json"
Expand Down Expand Up @@ -190,7 +191,9 @@ func (s *Server) RouteApplier(rpps ...RoutesPerPrefix) {
case ANY:
s.ANY(prefix+route.Path, route.Handler)
default:
s.slog.Warn("Cannot load route [%s](%s)", "route", prefix+route.Path, "verbe", route.Verbe)
s.slog.Warn("cannot load route",
slog.String("route", prefix+route.Path),
slog.String("verbe", route.Verbe))
}
}
}
Expand All @@ -215,7 +218,7 @@ func (s *Server) GetRouter() *router.Router {
if len(s.meta.docHandlers) > 0 {
for i := range s.meta.docHandlers {
h := s.meta.docHandlers[i]
s.slog.Info("load doc handler", "name", h.Name)
s.slog.Info("load doc handler", slog.String("name", h.Name))
r.ANY(s.meta.prefix+h.Path, s.CustomHandler(h.H))
}
}
Expand All @@ -230,11 +233,11 @@ func (s *Server) GetRouter() *router.Router {
// register socket.io (goplog) handlers
switch {
case s.meta.socketIOHF:
s.slog.Info("loading socket io handler func", "path", s.meta.socketIOPath)
s.slog.Info("loading socket io handler func", slog.String("path", s.meta.socketIOPath))
r.ANY(s.meta.socketIOPath,
fasthttpadaptor.NewFastHTTPHandlerFunc(s.meta.socketIOHandlerFunc))
case s.meta.socketIOH:
s.slog.Info("loading socket io handler", "path", s.meta.socketIOPath)
s.slog.Info("loading socket io handler", slog.String("path", s.meta.socketIOPath))
r.ANY(s.meta.socketIOPath,
fasthttpadaptor.NewFastHTTPHandler(s.meta.socketIOHandler))
}
Expand Down
47 changes: 19 additions & 28 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,22 +98,22 @@ func Shutdown() error {
// Start expose an server to an HTTP endpoint.
func (s *Server) Start(addr string) {
if s.meta.http2 {
s.slog.Warn("https endpoints required with http2, skipping", "address", addr)
s.slog.Warn("https endpoints required with http2, skipping", slog.String("address", addr))

return
}

s.internalHandler()
s.launcher.Start(func() {
s.slog.Debug("http server: starting", "address", addr)
s.slog.Debug("http server: starting", slog.String("address", addr))

go s.pollPingEndpoint(addr)

if e := s.internalInit(addr).ListenAndServe(addr); e != nil {
s.slog.Error("http server", "address", addr, "error", e)
s.slog.Error("http server", slog.String("address", addr), slog.Any("error", e))
}

s.slog.Info("http server: done", "address", addr)
s.slog.Info("http server: done", slog.String("address", addr))
})
}

Expand All @@ -124,13 +124,13 @@ func (s *Server) StartTLS(addr string, cfg tls.IConfig) {

tlsCfg, err := tls.GetTLSCfg(cfg, s.meta.http2)
if err != nil {
s.slog.Error("loading tls config", "error", err)
s.slog.Error("loading tls config", slog.Any("error", err))
os.Exit(2)
}

listner, err := tls.LoadListner(addr, tlsCfg)
if err != nil {
s.slog.Error("loading tls listener", "error", err)
s.slog.Error("loading tls listener", slog.Any("error", err))
os.Exit(3)
}

Expand All @@ -144,13 +144,14 @@ func (s *Server) StartTLS(addr string, cfg tls.IConfig) {
so2 := sOr2(s.meta.http2)

s.launcher.Start(func() {
s.slog.Debug(fmt.Sprintf("%s server: starting", so2), "address", addr)
defer s.slog.Info(fmt.Sprintf("%s server: done", so2), "address", addr)
s.slog.Debug(fmt.Sprintf("%s server: starting", so2), slog.String("address", addr))
defer s.slog.Info(fmt.Sprintf("%s server: done", so2), slog.String("address", addr))

go s.pollPingEndpoint(addr, cfg)

if e := server.Serve(listner); e != nil {
s.slog.Error(fmt.Sprintf("%s server", so2), "address", addr, "error", e)
s.slog.Error(fmt.Sprintf("%s server", so2),
slog.String("address", addr), slog.Any("error", e))
}
})
}
Expand Down Expand Up @@ -189,7 +190,7 @@ func (s *Server) DumpRoutes() map[string][]string {

for m, p := range all {
for i := range p {
s.slog.Info("routes", "name", m, "route", p[i])
s.slog.Info("routes", slog.String("name", m), slog.String("route", p[i]))
}
}

Expand Down Expand Up @@ -230,7 +231,7 @@ func (s *Server) internalInit(addr string) *fasthttp.Server {

poolOfServers = append(poolOfServers, worker)

s.slog.Debug("[+] server ", "address", addr, "total", len(poolOfServers))
s.slog.Debug("[+] server ", slog.String("address", addr), slog.Int("total", len(poolOfServers)))

return worker
}
Expand Down Expand Up @@ -266,14 +267,14 @@ func (s *Server) exitHandler(sig ...os.Signal) {

defer func() {
if e := s.Shutdown(); e != nil {
s.slog.Error("cannot stop the server", "error", e)
s.slog.Error("cannot stop the server", slog.Any("error", e))
}
}()

for s.ctx.Err() == nil {
select {
case si := <-c:
s.slog.Info("captured signal, exiting...", "signal", si)
s.slog.Info("captured signal, exiting...", slog.String("signal", si.String()))

return
case <-s.ctx.Done():
Expand All @@ -287,29 +288,19 @@ func (s *Server) exitHandler(sig ...os.Signal) {
//

// GetLogger return the used Log instance.
func (s *Server) GetStructuredLogger() *slog.Logger {
return s.slog
}
func (s *Server) GetStructuredLogger() *slog.Logger { return s.slog }

// GetLauncher return a pointer to the internal workerLauncher.
func (s *Server) GetLauncher() WorkerLauncher {
return s.launcher
}
func (s *Server) GetLauncher() WorkerLauncher { return s.launcher }

// GetContext return the context.Context used.
func (s *Server) GetContext() context.Context {
return s.ctx
}
func (s *Server) GetContext() context.Context { return s.ctx }

// GetContext return the server' context cancel func.
func (s *Server) GetCancel() context.CancelFunc {
return s.cancel
}
func (s *Server) GetCancel() context.CancelFunc { return s.cancel }

// IsReady return the channel on which `true` is send once the server is up.
func (s *Server) IsReady() chan bool {
return s.isReady
}
func (s *Server) IsReady() chan bool { return s.isReady }

// AddHandlers register the Handler handlers. Handler are executed from the top most.
func (s *Server) addHandlers(h ...Handler) *Server { //nolint: unparam
Expand Down

0 comments on commit 46ab52a

Please sign in to comment.