From 0fe98038b64f359f431b7590a9e9fc6266a5690a Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 8 Apr 2020 14:39:20 -0600 Subject: caddyhttp: Fix logging name associations by adding a default --- modules/caddyhttp/server.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) (limited to 'modules') diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index 72a67a7..ca83c5a 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -170,13 +170,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { repl.Set("http.response.latency", latency) logger := accLog - if s.Logs != nil && s.Logs.LoggerNames != nil { - if loggerName, ok := s.Logs.LoggerNames[r.Host]; ok { - logger = logger.Named(loggerName) - } else { - // see if there's a default log name to attach to - logger = logger.Named(s.Logs.LoggerNames[""]) - } + if loggerName := s.Logs.getLoggerName(r.Host); loggerName != "" { + logger = logger.Named(loggerName) } log := logger.Info @@ -205,8 +200,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err != nil { // prepare the error log logger := errLog - if s.Logs != nil && s.Logs.LoggerNames != nil { - logger = logger.Named(s.Logs.LoggerNames[r.Host]) + if loggerName := s.Logs.getLoggerName(r.Host); loggerName != "" { + logger = logger.Named(loggerName) } // get the values that will be used to log the error @@ -372,6 +367,10 @@ func (*HTTPErrorConfig) WithError(r *http.Request, err error) *http.Request { // ServerLogConfig describes a server's logging configuration. type ServerLogConfig struct { + // The logger name for all logs emitted by this server unless + // the hostname is found in the LoggerNames (logger_names) map. + LoggerName string `json:"log_name,omitempty"` + // LoggerNames maps request hostnames to a custom logger name. // For example, a mapping of "example.com" to "example" would // cause access logs from requests with a Host of example.com @@ -379,6 +378,13 @@ type ServerLogConfig struct { LoggerNames map[string]string `json:"logger_names,omitempty"` } +func (slc ServerLogConfig) getLoggerName(host string) string { + if loggerName, ok := slc.LoggerNames[host]; ok { + return loggerName + } + return slc.LoggerName +} + // errLogValues inspects err and returns the status code // to use, the error log message, and any extra fields. // If err is a HandlerError, the returned values will -- cgit v1.2.3