Skip to content

Commit

Permalink
Implemented middleware for slog
Browse files Browse the repository at this point in the history
  • Loading branch information
st-matskevich committed Nov 5, 2023
1 parent 6c7bc11 commit 10080dd
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 32 deletions.
3 changes: 1 addition & 2 deletions api/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"log/slog"

"github.com/gofiber/fiber/v2"
slogfiber "github.com/samber/slog-fiber"
)

type Controller interface {
Expand Down Expand Up @@ -32,6 +31,6 @@ func HandlerPrintf(c *fiber.Ctx, severity int, message string, v ...any) {
logger = slog.Error
}

args := append([]any{"request-id", slogfiber.GetRequestID(c)}, v...)
args := append([]any{GetRequestLogGroup(c)}, v...)
logger(message, args...)
}
80 changes: 80 additions & 0 deletions api/controller/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package controller

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

"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)

// Replace logs keys to allow GCP to parse logs correctly
// https://cloud.google.com/logging/docs/structured-logging
func CreateGCPLoggerAdapter() func(groups []string, a slog.Attr) slog.Attr {
return func(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case "level":
a.Key = "severity"
case "msg":
a.Key = "message"
}
return a
}
}

const CTX_REQUEST_ID = "requestID"

func CreateLoggerMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
requestID := uuid.New().String()
c.Context().SetUserValue(CTX_REQUEST_ID, requestID)
c.Set("X-Request-ID", requestID)

start := time.Now()

err := c.Next()

end := time.Now()
latency := end.Sub(start)
status := c.Response().StatusCode()
userAgent := string(c.Context().UserAgent())

logger := slog.Info
message := "Responeded to request with success code"
if status >= http.StatusInternalServerError {
logger = slog.Error
message = "Responeded to request with error code"
} else if status >= http.StatusBadRequest && status < http.StatusInternalServerError {
logger = slog.Warn
message = "Responeded to request with failure code"
}

logger(message,
"user-agent", userAgent,
"status", status,
"latency", latency,
GetRequestLogGroup(c),
)

return err
}
}

func GetRequestLogGroup(c *fiber.Ctx) slog.Attr {
id := GetRequestID(c)
return slog.Group("http-request",
"id", id,
"method", c.Method(),
"path", c.Path(),
)
}

func GetRequestID(c *fiber.Ctx) string {
requestID, ok := c.Context().UserValue(CTX_REQUEST_ID).(string)
if !ok {
return ""
}

return requestID
}
4 changes: 1 addition & 3 deletions api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ require (
github.com/lib/pq v1.10.9
github.com/minio/minio-go/v7 v7.0.63
github.com/nicksnyder/go-i18n/v2 v2.2.2
github.com/samber/slog-fiber v1.8.0
golang.org/x/text v0.14.0
)

Expand All @@ -33,11 +32,10 @@ require (
github.com/rivo/uniseg v0.4.4 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/stretchr/testify v1.8.4 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.50.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
go.opentelemetry.io/otel v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
Expand Down
8 changes: 0 additions & 8 deletions api/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJ
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-migrate/migrate/v4 v4.16.2 h1:8coYbMKUyInrFk1lfGfRovTLAW7PhWp8qQDT2iKfuoA=
github.com/golang-migrate/migrate/v4 v4.16.2/go.mod h1:pfcJX4nPHaVdc5nmdCikFBWtm+UBpiZjRNNsyBbp0/o=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
Expand Down Expand Up @@ -87,8 +85,6 @@ github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/samber/slog-fiber v1.8.0 h1:OubgFdS9q3uuKLSTjOe95tN8BCaV2j607Exjm2HmZf8=
github.com/samber/slog-fiber v1.8.0/go.mod h1:RgZVHaFlznYbKtaW4hdNwrBdKa46DayzTKdRmbSalN0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand All @@ -103,10 +99,6 @@ github.com/valyala/fasthttp v1.50.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.opentelemetry.io/otel v1.19.0 h1:MuS/TNf4/j4IXsZuJegVzI1cwut7Qc00344rgH7p8bs=
go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY=
go.opentelemetry.io/otel/trace v1.19.0 h1:DFVQmlVbfVeOuBRrwdtaehRrWiL1JoVs9CPIQ1Dzxpg=
go.opentelemetry.io/otel/trace v1.19.0/go.mod h1:mfaSyvGyEJEI0nyV2I4qhNQnbBOUUmYZpYojqMnX2vo=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
Expand Down
21 changes: 2 additions & 19 deletions api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
slogfiber "github.com/samber/slog-fiber"
"github.com/st-matskevich/audio-guide-bot/api/controller"
"github.com/st-matskevich/audio-guide-bot/api/provider/auth"
"github.com/st-matskevich/audio-guide-bot/api/provider/blob"
Expand All @@ -17,18 +16,8 @@ import (
)

func main() {
// Replace keys to allow GCP to parse logs correctly
// https://cloud.google.com/logging/docs/structured-logging
opts := slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case "level":
a.Key = "severity"
case "msg":
a.Key = "message"
}
return a
},
ReplaceAttr: controller.CreateGCPLoggerAdapter(),
}

logger := slog.New(slog.NewJSONHandler(os.Stdout, &opts))
Expand Down Expand Up @@ -69,13 +58,7 @@ func main() {
}))
}

// Set logger format to be equal to controller.HandlerPrintf
app.Use(slogfiber.New(slog.Default()))
/*app.Use(logger.New(logger.Config{
Format: "${time} ${method} ${path}: Returned ${status} in ${latency}\n",
TimeFormat: "2006/02/01 15:04:05",
DisableColors: true,
}))*/
app.Use(controller.CreateLoggerMiddleware())

botToken := os.Getenv("TELEGRAM_BOT_TOKEN")
paymentsToken := os.Getenv("TELEGRAM_PAYMENTS_TOKEN")
Expand Down

0 comments on commit 10080dd

Please sign in to comment.