Debian Codegraph @

modules/caddyhttp/logging.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyhttp
16
17 import (
18 "context"
19 "encoding/json"
20 "errors"
21 "log/slog"
22 "net"
23 "net/http"
24 "strings"
25 "sync"
26
27 "go.uber.org/zap"
28 "go.uber.org/zap/exp/zapslog"
29 "go.uber.org/zap/zapcore"
30
31 "github.com/caddyserver/caddy/v2"
32 )
33
34 func init() {
35 caddy.RegisterSlogHandlerFactory(func(handler slog.Handler, core zapcore.Core, moduleID string) slog.Handler {
36 return &extraFieldsSlogHandler{defaultHandler: handler, core: core, moduleID: moduleID}
37 })
38 }
39
40 // ServerLogConfig describes a server's logging configuration. If
41 // enabled without customization, all requests to this server are
42 // logged to the default logger; logger destinations may be
43 // customized per-request-host.
44 type ServerLogConfig struct {
45 // The default logger name for all logs emitted by this server for
46 // hostnames that are not in the logger_names map.
47 DefaultLoggerName string `json:"default_logger_name,omitempty"`
48
49 // LoggerNames maps request hostnames to one or more custom logger
50 // names. For example, a mapping of `"example.com": ["example"]` would
51 // cause access logs from requests with a Host of example.com to be
52 // emitted by a logger named "http.log.access.example". If there are
53 // multiple logger names, then the log will be emitted to all of them.
54 // If the logger name is an empty, the default logger is used, i.e.
55 // the logger "http.log.access".
56 //
57 // Keys must be hostnames (without ports), and may contain wildcards
58 // to match subdomains. The value is an array of logger names.
59 //
60 // For backwards compatibility, if the value is a string, it is treated
61 // as a single-element array.
62 LoggerNames map[string]StringArray `json:"logger_names,omitempty"`
63
64 // By default, all requests to this server will be logged if
65 // access logging is enabled. This field lists the request
66 // hosts for which access logging should be disabled.
67 SkipHosts []string `json:"skip_hosts,omitempty"`
68
69 // If true, requests to any host not appearing in the
70 // logger_names map will not be logged.
71 SkipUnmappedHosts bool `json:"skip_unmapped_hosts,omitempty"`
72
73 // If true, credentials that are otherwise omitted, will be logged.
74 // The definition of credentials is defined by https://fetch.spec.whatwg.org/#credentials,
75 // and this includes some request and response headers, i.e `Cookie`,
76 // `Set-Cookie`, `Authorization`, and `Proxy-Authorization`.
77 ShouldLogCredentials bool `json:"should_log_credentials,omitempty"`
78
79 // Log each individual handler that is invoked.
80 // Requires that the log emit at DEBUG level.
81 //
82 // NOTE: This may log the configuration of your
83 // HTTP handler modules; do not enable this in
84 // insecure contexts when there is sensitive
85 // data in the configuration.
86 //
87 // EXPERIMENTAL: Subject to change or removal.
88 Trace bool `json:"trace,omitempty"`
89 }
90
91 // wrapLogger wraps logger in one or more logger named
92 // according to user preferences for the given host.
93 func (slc ServerLogConfig) wrapLogger(logger *zap.Logger, req *http.Request) []*zap.Logger {
94 // using the `log_name` directive or the `access_logger_names` variable,
95 // the logger names can be overridden for the current request
96 if names := GetVar(req.Context(), AccessLoggerNameVarKey); names != nil {
97 if namesSlice, ok := names.([]any); ok {
98 loggers := make([]*zap.Logger, 0, len(namesSlice))
99 for _, loggerName := range namesSlice {
100 // no name, use the default logger
101 if loggerName == "" {
102 loggers = append(loggers, logger)
103 continue
104 }
105 // make a logger with the given name
106 loggers = append(loggers, logger.Named(loggerName.(string)))
107 }
108 return loggers
109 }
110 }
111
112 // get the hostname from the request, with the port number stripped
113 host, _, err := net.SplitHostPort(req.Host)
114 if err != nil {
115 host = req.Host
116 }
117
118 // get the logger names for this host from the config
119 hosts := slc.getLoggerHosts(host)
120
121 // make a list of named loggers, or the default logger
122 loggers := make([]*zap.Logger, 0, len(hosts))
123 for _, loggerName := range hosts {
124 // no name, use the default logger
125 if loggerName == "" {
126 loggers = append(loggers, logger)
127 continue
128 }
129 // make a logger with the given name
130 loggers = append(loggers, logger.Named(loggerName))
131 }
132 return loggers
133 }
134
135 func (slc ServerLogConfig) getLoggerHosts(host string) []string {
136 // try the exact hostname first
137 if hosts, ok := slc.LoggerNames[host]; ok {
138 return hosts
139 }
140
141 // try matching wildcard domains if other non-specific loggers exist
142 labels := strings.Split(host, ".")
143 for i := range labels {
144 if labels[i] == "" {
145 continue
146 }
147 labels[i] = "*"
148 wildcardHost := strings.Join(labels, ".")
149 if hosts, ok := slc.LoggerNames[wildcardHost]; ok {
150 return hosts
151 }
152 }
153
154 return []string{slc.DefaultLoggerName}
155 }
156
157 func (slc *ServerLogConfig) clone() *ServerLogConfig {
158 clone := &ServerLogConfig{
159 DefaultLoggerName: slc.DefaultLoggerName,
160 LoggerNames: make(map[string]StringArray),
161 SkipHosts: append([]string{}, slc.SkipHosts...),
162 SkipUnmappedHosts: slc.SkipUnmappedHosts,
163 ShouldLogCredentials: slc.ShouldLogCredentials,
164 }
165 for k, v := range slc.LoggerNames {
166 clone.LoggerNames[k] = append([]string{}, v...)
167 }
168 return clone
169 }
170
171 // StringArray is a slices of strings, but also accepts
172 // a single string as a value when JSON unmarshaling,
173 // converting it to a slice of one string.
174 type StringArray []string
175
176 // UnmarshalJSON satisfies json.Unmarshaler.
177 func (sa *StringArray) UnmarshalJSON(b []byte) error {
178 var jsonObj any
179 err := json.Unmarshal(b, &jsonObj)
180 if err != nil {
181 return err
182 }
183 switch obj := jsonObj.(type) {
184 case string:
185 *sa = StringArray([]string{obj})
186 return nil
187 case []any:
188 s := make([]string, 0, len(obj))
189 for _, v := range obj {
190 value, ok := v.(string)
191 if !ok {
192 return errors.New("unsupported type")
193 }
194 s = append(s, value)
195 }
196 *sa = StringArray(s)
197 return nil
198 }
199 return errors.New("unsupported type")
200 }
201
202 // errLogValues inspects err and returns the status code
203 // to use, the error log message, and any extra fields.
204 // If err is a HandlerError, the returned values will
205 // have richer information.
206 func errLogValues(err error) (status int, msg string, fields func() []zapcore.Field) {
207 var handlerErr HandlerError
208 if errors.As(err, &handlerErr) {
209 status = handlerErr.StatusCode
210 if handlerErr.Err == nil {
211 msg = err.Error()
212 } else {
213 msg = handlerErr.Err.Error()
214 }
215 fields = func() []zapcore.Field {
216 return []zapcore.Field{
217 zap.Int("status", handlerErr.StatusCode),
218 zap.String("err_id", handlerErr.ID),
219 zap.String("err_trace", handlerErr.Trace),
220 }
221 }
222 return status, msg, fields
223 }
224 fields = func() []zapcore.Field {
225 return []zapcore.Field{
226 zap.Error(err),
227 }
228 }
229 status = http.StatusInternalServerError
230 msg = err.Error()
231 return status, msg, fields
232 }
233
234 // ExtraLogFields is a list of extra fields to log with every request.
235 type ExtraLogFields struct {
236 fields []zapcore.Field
237 handlers sync.Map
238 }
239
240 // Add adds a field to the list of extra fields to log.
241 func (e *ExtraLogFields) Add(field zap.Field) {
242 e.handlers.Clear()
243 e.fields = append(e.fields, field)
244 }
245
246 // Set sets a field in the list of extra fields to log.
247 // If the field already exists, it is replaced.
248 func (e *ExtraLogFields) Set(field zap.Field) {
249 e.handlers.Clear()
250
251 for i := range e.fields {
252 if e.fields[i].Key == field.Key {
253 e.fields[i] = field
254 return
255 }
256 }
257 e.fields = append(e.fields, field)
258 }
259
260 func (e *ExtraLogFields) getSloggerHandler(handler *extraFieldsSlogHandler) (h slog.Handler) {
261 if existing, ok := e.handlers.Load(handler); ok {
262 return existing.(slog.Handler)
263 }
264
265 if handler.moduleID == "" {
266 h = zapslog.NewHandler(handler.core.With(e.fields))
267 } else {
268 h = zapslog.NewHandler(handler.core.With(e.fields), zapslog.WithName(handler.moduleID))
269 }
270
271 if handler.group != "" {
272 h = h.WithGroup(handler.group)
273 }
274 if handler.attrs != nil {
275 h = h.WithAttrs(handler.attrs)
276 }
277
278 e.handlers.Store(handler, h)
279
280 return h
281 }
282
283 const (
284 // Variable name used to indicate that this request
285 // should be omitted from the access logs
286 LogSkipVar string = "log_skip"
287
288 // For adding additional fields to the access logs
289 ExtraLogFieldsCtxKey caddy.CtxKey = "extra_log_fields"
290
291 // Variable name used to indicate the logger to be used
292 AccessLoggerNameVarKey string = "access_logger_names"
293 )
294
295 type extraFieldsSlogHandler struct {
296 defaultHandler slog.Handler
297 core zapcore.Core
298 moduleID string
299 group string
300 attrs []slog.Attr
301 }
302
303 func (e *extraFieldsSlogHandler) Enabled(ctx context.Context, level slog.Level) bool {
304 return e.defaultHandler.Enabled(ctx, level)
305 }
306
307 func (e *extraFieldsSlogHandler) Handle(ctx context.Context, record slog.Record) error {
308 if elf, ok := ctx.Value(ExtraLogFieldsCtxKey).(*ExtraLogFields); ok {
309 return elf.getSloggerHandler(e).Handle(ctx, record)
310 }
311
312 return e.defaultHandler.Handle(ctx, record)
313 }
314
315 func (e *extraFieldsSlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
316 return &extraFieldsSlogHandler{
317 e.defaultHandler.WithAttrs(attrs),
318 e.core,
319 e.moduleID,
320 e.group,
321 append(e.attrs, attrs...),
322 }
323 }
324
325 func (e *extraFieldsSlogHandler) WithGroup(name string) slog.Handler {
326 return &extraFieldsSlogHandler{
327 e.defaultHandler.WithGroup(name),
328 e.core,
329 e.moduleID,
330 name,
331 e.attrs,
332 }
333 }