sftpgo-mirror/logger/request_logger.go

80 lines
2.1 KiB
Go
Raw Normal View History

2019-07-20 10:26:52 +00:00
package logger
import (
"fmt"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
2019-07-20 10:26:52 +00:00
"github.com/rs/zerolog"
2021-06-26 05:31:41 +00:00
"github.com/drakkan/sftpgo/v2/metrics"
2019-07-20 10:26:52 +00:00
)
2019-07-30 18:51:29 +00:00
// StructuredLogger defines a simple wrapper around zerolog logger.
// It implements chi.middleware.LogFormatter interface
2019-07-20 10:26:52 +00:00
type StructuredLogger struct {
Logger *zerolog.Logger
}
2019-07-30 18:51:29 +00:00
// StructuredLoggerEntry defines a log entry.
// It implements chi.middleware.LogEntry interface
2019-07-20 10:26:52 +00:00
type StructuredLoggerEntry struct {
2019-07-30 18:51:29 +00:00
// The zerolog logger
2019-07-20 10:26:52 +00:00
Logger *zerolog.Logger
2019-07-30 18:51:29 +00:00
// fields to write in the log
2019-07-20 10:26:52 +00:00
fields map[string]interface{}
}
2019-07-30 18:51:29 +00:00
// NewStructuredLogger returns a chi.middleware.RequestLogger using our StructuredLogger.
// This structured logger is called by the chi.middleware.Logger handler to log each HTTP request
2019-07-20 10:26:52 +00:00
func NewStructuredLogger(logger *zerolog.Logger) func(next http.Handler) http.Handler {
return middleware.RequestLogger(&StructuredLogger{logger})
}
2019-07-30 18:51:29 +00:00
// NewLogEntry creates a new log entry for an HTTP request
2019-07-20 10:26:52 +00:00
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
fields := map[string]interface{}{
"remote_addr": r.RemoteAddr,
"proto": r.Proto,
"method": r.Method,
"user_agent": r.UserAgent(),
"uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)}
reqID := middleware.GetReqID(r.Context())
if reqID != "" {
fields["request_id"] = reqID
}
return &StructuredLoggerEntry{Logger: l.Logger, fields: fields}
}
2019-07-30 18:51:29 +00:00
// Write logs a new entry at the end of the HTTP request
func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
metrics.HTTPRequestServed(status)
l.Logger.Info().
Timestamp().
Str("sender", "httpd").
Fields(l.fields).
Int("resp_status", status).
Int("resp_size", bytes).
Int64("elapsed_ms", elapsed.Nanoseconds()/1000000).
Send()
2019-07-20 10:26:52 +00:00
}
// Panic logs panics
func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
l.Logger.Error().
Timestamp().
Str("sender", "httpd").
Fields(l.fields).
Str("stack", string(stack)).
Str("panic", fmt.Sprintf("%+v", v)).
Send()
2019-07-20 10:26:52 +00:00
}