67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package presenter
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
"tokenbridge-monitor/logging"
|
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func NewRequestLogger(logger logging.Logger) func(next http.Handler) http.Handler {
|
|
return middleware.RequestLogger(&StructuredLogger{logger})
|
|
}
|
|
|
|
type StructuredLogger struct {
|
|
Logger logging.Logger
|
|
}
|
|
|
|
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
|
|
entry := &StructuredLoggerEntry{Logger: l.Logger}
|
|
logFields := logrus.Fields{}
|
|
|
|
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
|
|
logFields["req_id"] = reqID
|
|
}
|
|
|
|
scheme := "http"
|
|
if r.TLS != nil {
|
|
scheme = "https"
|
|
}
|
|
logFields["http_scheme"] = scheme
|
|
logFields["http_proto"] = r.Proto
|
|
logFields["http_method"] = r.Method
|
|
logFields["remote_addr"] = r.RemoteAddr
|
|
|
|
logFields["uri"] = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)
|
|
|
|
entry.Logger = entry.Logger.WithFields(logFields)
|
|
|
|
entry.Logger.Infoln("request started")
|
|
|
|
return entry
|
|
}
|
|
|
|
type StructuredLoggerEntry struct {
|
|
Logger logrus.FieldLogger
|
|
}
|
|
|
|
func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
|
|
l.Logger = l.Logger.WithFields(logrus.Fields{
|
|
"resp_status": status,
|
|
"resp_bytes_length": bytes,
|
|
"resp_elapsed_ms": elapsed,
|
|
})
|
|
|
|
l.Logger.Infoln("request completed")
|
|
}
|
|
|
|
func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
|
|
l.Logger = l.Logger.WithFields(logrus.Fields{
|
|
"stack": string(stack),
|
|
"panic": fmt.Sprintf("%+v", v),
|
|
})
|
|
}
|