pgweb/pkg/api/logger.go

91 lines
1.6 KiB
Go
Raw Permalink Normal View History

package api
import (
"net/http"
2022-12-02 12:20:58 -06:00
"regexp"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
2022-12-02 12:20:58 -06:00
var (
logger *logrus.Logger
reConnectToken = regexp.MustCompile("/connect/(.*)")
)
2022-12-02 11:45:23 -06:00
func init() {
if logger == nil {
logger = logrus.New()
}
}
// TODO: Move this into server struct when it's ready
func SetLogger(l *logrus.Logger) {
logger = l
}
func RequestLogger(logger *logrus.Logger) gin.HandlerFunc {
2022-12-01 12:49:24 -06:00
debug := logger.Level > logrus.InfoLevel
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
// Process request
c.Next()
2022-12-02 12:20:58 -06:00
if !debug {
// Skip static assets logging
if strings.Contains(path, "/static/") {
return
}
path = sanitizeLogPath(path)
}
status := c.Writer.Status()
end := time.Now()
latency := end.Sub(start)
fields := logrus.Fields{
"status": status,
"method": c.Request.Method,
"remote_addr": c.ClientIP(),
"duration": latency,
2022-12-06 12:09:21 -06:00
"path": path,
}
if err := c.Errors.Last(); err != nil {
fields["error"] = err.Error()
}
2022-12-01 12:49:24 -06:00
// Additional fields for debugging
if debug {
fields["raw_query"] = c.Request.URL.RawQuery
2022-12-06 12:30:43 -06:00
if c.Request.Method != http.MethodGet {
fields["raw_form"] = c.Request.Form
}
2022-12-01 12:49:24 -06:00
}
2022-12-06 12:09:21 -06:00
entry := logger.WithFields(fields)
msg := "http_request"
switch {
case status >= http.StatusBadRequest && status < http.StatusInternalServerError:
2022-12-03 15:11:45 -06:00
entry.Warn(msg)
case status >= http.StatusInternalServerError:
2022-12-03 15:11:45 -06:00
entry.Error(msg)
default:
2022-12-03 15:11:45 -06:00
entry.Info(msg)
}
}
}
2022-12-02 12:20:58 -06:00
func sanitizeLogPath(str string) string {
return reConnectToken.ReplaceAllString(str, "/connect/REDACTED")
}