Debian Codegraph @

internal/zhttp/logging.go

raw symbols SCIP
1 package zhttp
2
3 import (
4 "context"
5 "fmt"
6 stdlog "log"
7 "net/http"
8 "os"
9 "strings"
10 "time"
11
12 "github.com/rs/zerolog"
13 "github.com/rs/zerolog/log"
14 "github.com/sassoftware/relic/v7/internal/logrotate"
15 )
16
17 type ctxKey int
18
19 var (
20 ctxAccessCallbacks ctxKey = 1
21 ctxDontLog ctxKey = 2
22 )
23
24 const rfc3339Milli = "2006-01-02T15:04:05.000Z07:00" // RFC3339 with 3 decimal places, padded
25
26 // SetupLogging initializes zerolog with reasonable defaults
27 func SetupLogging(levelName, logFile string) error {
28 zerolog.TimeFieldFormat = rfc3339Milli
29 zerolog.DurationFieldInteger = true
30 switch logFile {
31 case "-":
32 // write JSON to stderr
33 case "":
34 // write pretty text to stderr
35 log.Logger = log.Logger.Output(zerolog.ConsoleWriter{
36 Out: os.Stderr,
37 TimeFormat: "15:04:05",
38 })
39 default:
40 // write JSON to file
41 w, err := logrotate.NewWriter(logFile)
42 if err != nil {
43 return fmt.Errorf("log_file: %w", err)
44 }
45 log.Logger = log.Logger.Output(w)
46 }
47 // set default log level
48 if levelName == "" {
49 levelName = zerolog.InfoLevel.String()
50 }
51 level, err := zerolog.ParseLevel(levelName)
52 if err != nil {
53 return fmt.Errorf("log_level: %w", err)
54 }
55 log.Logger = log.Logger.Level(level)
56 // pass stdlib logger through
57 stdlog.SetFlags(0)
58 stdlog.SetOutput(log.Logger)
59 return nil
60 }
61
62 // LoggingMiddleware creates a logging context for each request, and emits an
63 // access log entry at the completion of the request.
64 func LoggingMiddleware(opts ...LoggingOption) func(http.Handler) http.Handler {
65 cfg := loggingConfig{
66 logger: log.Logger,
67 now: time.Now,
68 }
69 for _, o := range opts {
70 o(&cfg)
71 }
72 return func(next http.Handler) http.Handler {
73 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
74 // Make a new log context for the scope of the request with basic
75 // request metadata suitable for every log entry
76 lc := cfg.logger.With().
77 Str("ip", StripPort(req.RemoteAddr)).
78 Str("req_id", req.Header.Get("X-Request-Id"))
79 // build request context and execute the next handler
80 baseLogger := lc.Logger()
81 ctx := req.Context()
82 ctx = baseLogger.WithContext(ctx)
83 var callbacks []AccessLogCallback
84 var dontLog bool
85 ctx = context.WithValue(ctx, ctxAccessCallbacks, &callbacks)
86 ctx = context.WithValue(ctx, ctxDontLog, &dontLog)
87 start := cfg.now()
88 lw := &Logger{
89 ResponseWriter: rw,
90 Now: cfg.now,
91 }
92 req = req.WithContext(ctx)
93 next.ServeHTTP(lw, req)
94 // emit the access log entry
95 if !dontLog {
96 // Logger.WithContext makes a copy of the logger to put into
97 // ctx, so make sure we use that as a base to get the effects of
98 // any UpdateContext calls from inside the view funcs.
99 logger := zerolog.Ctx(ctx)
100 ev := logger.Info().
101 Str("method", req.Method).
102 Stringer("url", req.URL).
103 Int("status", lw.Status()).
104 Int64("len", lw.Length()).
105 Dur("dur", cfg.now().Sub(start)).
106 Dur("ttfb", lw.Started().Sub(start)).
107 Str("ua", req.UserAgent())
108 for _, cb := range callbacks {
109 cb(ev)
110 }
111 ev.Send()
112 }
113 })
114 }
115 }
116
117 type AccessLogCallback func(*zerolog.Event)
118
119 // AppendAccessLog adds a callback function which will be invoked to amend the
120 // access log with additional fields.
121 func AppendAccessLog(req *http.Request, f AccessLogCallback) {
122 AppendAccessLogContext(req.Context(), f)
123 }
124
125 // AppendAccessLog adds a callback function which will be invoked to amend the
126 // access log with additional fields.
127 func AppendAccessLogContext(ctx context.Context, f AccessLogCallback) {
128 callbacks, _ := ctx.Value(ctxAccessCallbacks).(*[]AccessLogCallback)
129 if callbacks != nil {
130 *callbacks = append(*callbacks, f)
131 }
132 }
133
134 // DontLog marks that the current request should not generate an access log
135 // entry
136 func DontLog(req *http.Request) {
137 dontLog, _ := req.Context().Value(ctxDontLog).(*bool)
138 if dontLog != nil {
139 *dontLog = true
140 }
141 }
142
143 type loggingConfig struct {
144 logger zerolog.Logger
145 now func() time.Time
146 }
147
148 type LoggingOption func(*loggingConfig)
149
150 // WithLogger sets the base logger for the middleware
151 func WithLogger(logger zerolog.Logger) LoggingOption {
152 return func(lc *loggingConfig) {
153 lc.logger = logger
154 }
155 }
156
157 // StripPort returns just the IP part from e.g. Request.RemoteAddr
158 func StripPort(clientIP string) string {
159 i := strings.IndexByte(clientIP, ':')
160 j := strings.IndexByte(clientIP, ']')
161 if j > 1 && clientIP[0] == '[' {
162 // [fe80::]:1234
163 return clientIP[1:j]
164 } else if i > 0 && strings.Count(clientIP, ":") == 1 {
165 // 127.0.0.1:1234
166 return clientIP[:i]
167 }
168 return clientIP
169 }