implemented log levels and structured log with slog
Some checks failed
Tests / Run Go Tests (push) Failing after 1m36s

This commit is contained in:
2025-10-13 22:33:48 +02:00
parent ea8e78fd9f
commit 5001f24d9b
9 changed files with 21 additions and 19 deletions

View File

@@ -5,8 +5,7 @@ import (
"arbeitszeitmessung/helper"
"arbeitszeitmessung/models"
"context"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"time"
@@ -17,23 +16,25 @@ import (
func main() {
var err error
var logLevel slog.LevelVar
logLevel.Set(slog.LevelWarn)
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: &logLevel}))
slog.SetDefault(logger)
err = godotenv.Load(".env")
if err != nil {
log.Println("No .env file found in directory!")
slog.Info("No .env file found in directory!")
}
if helper.GetEnv("GO_ENV", "production") == "debug" {
log.Println("Debug mode enabled")
log.Println("Environment Variables")
logLevel.Set(slog.LevelDebug)
envs := os.Environ()
for _, e := range envs {
fmt.Println(e)
}
slog.Debug("Debug mode enabled", "Environment Variables", envs)
}
models.DB, err = OpenDatabase()
if err != nil {
log.Fatal(err)
slog.Error("Error while opening the database", "Error", err)
}
fs := http.FileServer(http.Dir("./static"))
@@ -58,14 +59,15 @@ func main() {
serverSessionMiddleware := endpoints.Session.LoadAndSave(server)
// starting the http server
fmt.Printf("Server is running at http://localhost:%s\n", helper.GetEnv("EXPOSED_PORT", "8080"))
log.Fatal(http.ListenAndServe(":8080", serverSessionMiddleware))
slog.Info("Server is running at http://localhost:8080")
slog.Error("Error starting Server", "Error", http.ListenAndServe(":8080", serverSessionMiddleware))
}
func ParamsMiddleware(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
queryParams := r.URL.Query()
ctx := context.WithValue(r.Context(), "urlParams", queryParams)
slog.Debug("ParamsMiddleware added urlParams", slog.Any("urlParams", queryParams))
next.ServeHTTP(w, r.WithContext(ctx))
})
}