request_logger.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package logger
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "net"
  19. "net/http"
  20. "time"
  21. "github.com/go-chi/chi/v5/middleware"
  22. "github.com/rs/zerolog"
  23. "github.com/drakkan/sftpgo/v2/internal/metric"
  24. )
  25. // StructuredLogger defines a simple wrapper around zerolog logger.
  26. // It implements chi.middleware.LogFormatter interface
  27. type StructuredLogger struct {
  28. Logger *zerolog.Logger
  29. }
  30. // StructuredLoggerEntry defines a log entry.
  31. // It implements chi.middleware.LogEntry interface
  32. type StructuredLoggerEntry struct {
  33. // The zerolog logger
  34. Logger *zerolog.Logger
  35. // fields to write in the log
  36. fields map[string]any
  37. }
  38. // NewStructuredLogger returns a chi.middleware.RequestLogger using our StructuredLogger.
  39. // This structured logger is called by the chi.middleware.Logger handler to log each HTTP request
  40. func NewStructuredLogger(logger *zerolog.Logger) func(next http.Handler) http.Handler {
  41. return middleware.RequestLogger(&StructuredLogger{logger})
  42. }
  43. // NewLogEntry creates a new log entry for an HTTP request
  44. func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
  45. scheme := "http"
  46. cipherSuite := ""
  47. if r.TLS != nil {
  48. scheme = "https"
  49. cipherSuite = tls.CipherSuiteName(r.TLS.CipherSuite)
  50. }
  51. fields := map[string]any{
  52. "local_addr": getLocalAddress(r),
  53. "remote_addr": r.RemoteAddr,
  54. "proto": r.Proto,
  55. "method": r.Method,
  56. "user_agent": r.UserAgent(),
  57. "uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI),
  58. "cipher_suite": cipherSuite,
  59. }
  60. reqID := middleware.GetReqID(r.Context())
  61. if reqID != "" {
  62. fields["request_id"] = reqID
  63. }
  64. return &StructuredLoggerEntry{Logger: l.Logger, fields: fields}
  65. }
  66. // Write logs a new entry at the end of the HTTP request
  67. func (l *StructuredLoggerEntry) Write(status, bytes int, _ http.Header, elapsed time.Duration, _ any) {
  68. metric.HTTPRequestServed(status)
  69. var ev *zerolog.Event
  70. if status >= http.StatusInternalServerError {
  71. ev = l.Logger.Error()
  72. } else if status >= http.StatusBadRequest {
  73. ev = l.Logger.Warn()
  74. } else {
  75. ev = l.Logger.Debug()
  76. }
  77. ev.
  78. Timestamp().
  79. Str("sender", "httpd").
  80. Fields(l.fields).
  81. Int("resp_status", status).
  82. Int("resp_size", bytes).
  83. Int64("elapsed_ms", elapsed.Nanoseconds()/1000000).
  84. Send()
  85. }
  86. // Panic logs panics
  87. func (l *StructuredLoggerEntry) Panic(v any, stack []byte) {
  88. l.Logger.Error().
  89. Timestamp().
  90. Str("sender", "httpd").
  91. Fields(l.fields).
  92. Str("stack", string(stack)).
  93. Str("panic", fmt.Sprintf("%+v", v)).
  94. Send()
  95. }
  96. func getLocalAddress(r *http.Request) string {
  97. if r == nil {
  98. return ""
  99. }
  100. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  101. if ok {
  102. return localAddr.String()
  103. }
  104. return ""
  105. }