request_logger.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright (C) 2019-2023 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. "fmt"
  17. "net"
  18. "net/http"
  19. "time"
  20. "github.com/go-chi/chi/v5/middleware"
  21. "github.com/rs/zerolog"
  22. "github.com/drakkan/sftpgo/v2/internal/metric"
  23. )
  24. // StructuredLogger defines a simple wrapper around zerolog logger.
  25. // It implements chi.middleware.LogFormatter interface
  26. type StructuredLogger struct {
  27. Logger *zerolog.Logger
  28. }
  29. // StructuredLoggerEntry defines a log entry.
  30. // It implements chi.middleware.LogEntry interface
  31. type StructuredLoggerEntry struct {
  32. // The zerolog logger
  33. Logger *zerolog.Logger
  34. // fields to write in the log
  35. fields map[string]any
  36. }
  37. // NewStructuredLogger returns a chi.middleware.RequestLogger using our StructuredLogger.
  38. // This structured logger is called by the chi.middleware.Logger handler to log each HTTP request
  39. func NewStructuredLogger(logger *zerolog.Logger) func(next http.Handler) http.Handler {
  40. return middleware.RequestLogger(&StructuredLogger{logger})
  41. }
  42. // NewLogEntry creates a new log entry for an HTTP request
  43. func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
  44. scheme := "http"
  45. if r.TLS != nil {
  46. scheme = "https"
  47. }
  48. fields := map[string]any{
  49. "local_addr": getLocalAddress(r),
  50. "remote_addr": r.RemoteAddr,
  51. "proto": r.Proto,
  52. "method": r.Method,
  53. "user_agent": r.UserAgent(),
  54. "uri": fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)}
  55. reqID := middleware.GetReqID(r.Context())
  56. if reqID != "" {
  57. fields["request_id"] = reqID
  58. }
  59. return &StructuredLoggerEntry{Logger: l.Logger, fields: fields}
  60. }
  61. // Write logs a new entry at the end of the HTTP request
  62. func (l *StructuredLoggerEntry) Write(status, bytes int, _ http.Header, elapsed time.Duration, _ any) {
  63. metric.HTTPRequestServed(status)
  64. l.Logger.Info().
  65. Timestamp().
  66. Str("sender", "httpd").
  67. Fields(l.fields).
  68. Int("resp_status", status).
  69. Int("resp_size", bytes).
  70. Int64("elapsed_ms", elapsed.Nanoseconds()/1000000).
  71. Send()
  72. }
  73. // Panic logs panics
  74. func (l *StructuredLoggerEntry) Panic(v any, stack []byte) {
  75. l.Logger.Error().
  76. Timestamp().
  77. Str("sender", "httpd").
  78. Fields(l.fields).
  79. Str("stack", string(stack)).
  80. Str("panic", fmt.Sprintf("%+v", v)).
  81. Send()
  82. }
  83. func getLocalAddress(r *http.Request) string {
  84. if r == nil {
  85. return ""
  86. }
  87. localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
  88. if ok {
  89. return localAddr.String()
  90. }
  91. return ""
  92. }