1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-12-23 22:11:10 +02:00
Files
imgproxy/server/logging.go
Sergei Aleksandrovich e33254005d Refactored errors (#1578)
* Refactored errors

* Make monitoring and errorreport accept `errctx.Error` instead of `error`

* Add server.Error; Remove category from errctx; Make HTTP handlers respond with *server.Error

* Remove stackSkip from errctx.Wrap; Add errctx.WrapWithStackSkip
2025-11-20 01:26:21 +06:00

72 lines
1.3 KiB
Go

package server
import (
"context"
"fmt"
"log/slog"
"net"
"net/http"
"github.com/imgproxy/imgproxy/v3/errctx"
)
func LogRequest(reqID string, r *http.Request) {
path := r.RequestURI
clientIP, _, _ := net.SplitHostPort(r.RemoteAddr)
slog.Info(
fmt.Sprintf("Started %s", path),
"request_id", reqID,
"method", r.Method,
"client_ip", clientIP,
)
}
func LogResponse(
reqID string,
r *http.Request,
status int,
err errctx.Error,
additional ...slog.Attr,
) {
var level slog.Level
switch {
case status >= 500 || (err != nil && err.StatusCode() >= 500):
level = slog.LevelError
case status >= 400:
level = slog.LevelWarn
default:
level = slog.LevelInfo
}
clientIP, _, _ := net.SplitHostPort(r.RemoteAddr)
attrs := []slog.Attr{
slog.String("request_id", reqID),
slog.String("method", r.Method),
slog.Int("status", status),
slog.String("client_ip", clientIP),
}
if err != nil {
attrs = append(attrs, slog.String("error", err.Error()))
if level >= slog.LevelError {
if stack := err.FormatStack(); len(stack) > 0 {
attrs = append(attrs, slog.String("stack", stack))
}
}
}
attrs = append(attrs, additional...)
slog.LogAttrs(
context.Background(),
level,
fmt.Sprintf("Completed in %s %s", requestStartedAt(r.Context()), r.RequestURI),
attrs...,
)
}