Skip to content

Commit

Permalink
improvement of logging, introduction of panic recover
Browse files Browse the repository at this point in the history
  • Loading branch information
martinjirku committed Dec 18, 2023
1 parent eeb46aa commit e5af9eb
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 3 deletions.
1 change: 0 additions & 1 deletion handlers/Index.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ func (h *IndexHandler) Get(w http.ResponseWriter, r *http.Request) {
}

func (h *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Log.Info("request", slog.String("method", r.Method), slog.String("path", r.URL.Path))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if r.Method == http.MethodPost {
// todo: handle POST
Expand Down
19 changes: 17 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"jirku.sk/mcmamina/handlers"
"jirku.sk/mcmamina/pkg/middleware"
"jirku.sk/mcmamina/services"
)

Expand All @@ -26,7 +27,7 @@ const (
var distFS embed.FS

func main() {
log := slog.Default()
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
err := godotenv.Load()
if err != nil {
log.Error("Error loading .env file", slog.Any("error", err))
Expand All @@ -44,6 +45,7 @@ type configuration struct {
func setupWebserver(log *slog.Logger, calendarService *services.CalendarService) {
config := configuration{}
router := mux.NewRouter()

flag.StringVar(&config.publicPath, "public", "", "Usage description of the flag")
flag.StringVar(&config.host, "host", "0.0.0.0", "specify the app host")
flag.IntVar(&config.port, "port", 8080, "specfiy the port application will listen")
Expand All @@ -69,8 +71,13 @@ func setupWebserver(log *slog.Logger, calendarService *services.CalendarService)
workingFolder = os.DirFS(config.publicPath)
}

cssService := services.NewCSS(workingFolder, log)
cssService := services.NewCSS(workingFolder, serviceLog(log, "css"))
sponsorService := services.NewSponsorService()

// Logger middleware
router.Use(middleware.Recover(middlwareLog(log, "recover")))
router.Use(middleware.Logger(middlwareLog(log, "logger")))

router.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
Expand Down Expand Up @@ -132,3 +139,11 @@ func getContentType(filePath string) string {
func validatePort(port int) bool {
return port > 0 && port <= 65535
}

func middlwareLog(log *slog.Logger, name string) *slog.Logger {
return log.With(slog.String("type", "middleware"), slog.String("name", name))
}

func serviceLog(log *slog.Logger, name string) *slog.Logger {
return log.With(slog.String("type", "service"), slog.String("name", name))
}
20 changes: 20 additions & 0 deletions pkg/middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package middleware

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

func Logger(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info("request",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("referer", r.Referer()),
slog.String("user-agent", r.UserAgent()),
)
next.ServeHTTP(w, r)
})
}
}
21 changes: 21 additions & 0 deletions pkg/middleware/recover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package middleware

import (
"log/slog"
"net/http"
"runtime/debug"
)

func Recover(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
logger.Error("Recovered from panic", slog.Any("error", err), slog.Any("stack", debug.Stack()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}

0 comments on commit e5af9eb

Please sign in to comment.