addLogField adds the log field to the request's extra log fields. If buf is not nil, it contains the buffered response body for special response body placeholders.
(r *http.Request, buf *bytes.Buffer)
| 118 | // If buf is not nil, it contains the buffered response body for special |
| 119 | // response body placeholders. |
| 120 | func (h LogAppend) addLogField(r *http.Request, buf *bytes.Buffer) { |
| 121 | ctx := r.Context() |
| 122 | |
| 123 | vars := ctx.Value(caddyhttp.VarsCtxKey).(map[string]any) |
| 124 | repl := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 125 | extra := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields) |
| 126 | |
| 127 | var varValue any |
| 128 | |
| 129 | // Handle special case placeholders for response body |
| 130 | if h.Value == placeholderResponseBody { |
| 131 | if buf != nil { |
| 132 | varValue = buf.String() |
| 133 | } else { |
| 134 | varValue = "" |
| 135 | } |
| 136 | } else if h.Value == placeholderResponseBodyBase64 { |
| 137 | if buf != nil { |
| 138 | varValue = base64.StdEncoding.EncodeToString(buf.Bytes()) |
| 139 | } else { |
| 140 | varValue = "" |
| 141 | } |
| 142 | } else if strings.HasPrefix(h.Value, "{") && |
| 143 | strings.HasSuffix(h.Value, "}") && |
| 144 | strings.Count(h.Value, "{") == 1 { |
| 145 | // the value looks like a placeholder, so get its value |
| 146 | varValue, _ = repl.Get(strings.Trim(h.Value, "{}")) |
| 147 | } else if val, ok := vars[h.Value]; ok { |
| 148 | // the value is a key in the vars map |
| 149 | varValue = val |
| 150 | } else { |
| 151 | // the value is a constant string |
| 152 | varValue = h.Value |
| 153 | } |
| 154 | |
| 155 | // Add the field to the extra log fields. |
| 156 | // We use zap.Any because it will reflect |
| 157 | // to the correct type for us. |
| 158 | extra.Add(zap.Any(h.Key, varValue)) |
| 159 | } |
| 160 | |
| 161 | const ( |
| 162 | // Special placeholder values that are handled by log_append |