Skip to content

Instantly share code, notes, and snippets.

@shaunlee
Last active June 22, 2024 01:44
Show Gist options
  • Save shaunlee/95e5e8c5a733d73a98330158192b1f81 to your computer and use it in GitHub Desktop.
Save shaunlee/95e5e8c5a733d73a98330158192b1f81 to your computer and use it in GitHub Desktop.
HTTP request/response logger
package tracker
import (
"fmt"
"github.com/gofiber/fiber/v2"
"log"
"strings"
"time"
)
func New() fiber.Handler {
return func(c *fiber.Ctx) error {
t := time.Now()
id := fmt.Sprintf("%x", t.Nanosecond())
ip := c.IP()
method := c.Method()
path := c.OriginalURL()
msg := ""
ct := c.Get("Content-Type")
if strings.HasPrefix(ct, "application/json") || strings.HasPrefix(ct, "application/x-www-form-urlencoded") {
if body := c.Body(); len(body) > 0 {
msg = string(body)
}
}
log.Println(id, ip, "<-", method, path, msg, c.Get("User-Agent"))
err := c.Next()
code := c.Response().Header.StatusCode()
if err != nil {
if ferr, ok := err.(*fiber.Error); ok {
code = ferr.Code
} else {
code = 500
}
}
rmsg := ""
ct = c.GetRespHeader("Content-Type")
if strings.HasPrefix(ct, "application/json") || strings.HasPrefix(ct, "text/plain") {
if body := c.Response().Body(); len(body) > 0 {
rmsg = string(body)
}
}
log.Println(id, ip, "->", method, code, path, time.Since(t), rmsg)
return err
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment