Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 12, 19:30 UTC
caddyhttp: Add `uuid` to access logs when used (#5859)
Francis Lavoie committed
Dec 13, 2023 at 17:40 UTC
3d7d60f7cf8d1d721f9a577e71ca56f4ad80bc71
3 files changed
+22
caddyconfig/httpcaddyfile/shorthands.go
+1
@@ -64,6 +64,7 @@ func placeholderShorthands() []string {
64
"{remote_port}", "{http.request.remote.port}",
65
"{scheme}", "{http.request.scheme}",
66
"{uri}", "{http.request.uri}",
67
+ "{uuid}", "{http.request.uuid}",
68
"{tls_cipher}", "{http.request.tls.cipher_suite}",
69
"{tls_version}", "{http.request.tls.version}",
70
"{tls_client_fingerprint}", "{http.request.tls.client.fingerprint}",
modules/caddyhttp/logging.go
+12
@@ -151,6 +151,18 @@ func (e *ExtraLogFields) Add(field zap.Field) {
151
e.fields = append(e.fields, field)
152
}
153
154
+// Set sets a field in the list of extra fields to log.
155
+// If the field already exists, it is replaced.
156
+func (e *ExtraLogFields) Set(field zap.Field) {
157
+ for i := range e.fields {
158
+ if e.fields[i].Key == field.Key {
159
+ e.fields[i] = field
160
+ return
161
+ }
162
+ }
163
+ e.fields = append(e.fields, field)
164
+}
165
+
166
const (
167
// Variable name used to indicate that this request
168
// should be omitted from the access logs
modules/caddyhttp/replacer.go
+9
@@ -40,6 +40,7 @@ import (
40
"time"
41
42
"github.com/google/uuid"
43
+ "go.uber.org/zap"
44
45
"github.com/caddyserver/caddy/v2"
46
"github.com/caddyserver/caddy/v2/modules/caddytls"
@@ -157,9 +158,17 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
158
case "http.request.duration_ms":
159
start := GetVar(req.Context(), "start_time").(time.Time)
160
return time.Since(start).Seconds() * 1e3, true // multiply seconds to preserve decimal (see #4666)
161
+
162
case "http.request.uuid":
163
+ // fetch the UUID for this request
164
id := GetVar(req.Context(), "uuid").(*requestID)
165
+
166
+ // set it to this request's access log
167
+ extra := req.Context().Value(ExtraLogFieldsCtxKey).(*ExtraLogFields)
168
+ extra.Set(zap.String("uuid", id.String()))
169
+
170
return id.String(), true
171
+
172
case "http.request.body":
173
if req.Body == nil {
174
return "", true