Skip to content

Commit

Permalink
caddyhttp: Better host matching for logger names (fix #3488) (#3522)
Browse files Browse the repository at this point in the history
First try an exact lookup like before, but if it fails, strip the port
and try again. example.com:1234 should still use a logger keyed for
example.com if there is no key example.com:1234.
  • Loading branch information
mholt authored Jun 26, 2020
1 parent 61b7002 commit 21c00a3
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions modules/caddyhttp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,19 +453,35 @@ func (slc ServerLogConfig) wrapLogger(logger *zap.Logger, host string) *zap.Logg
}

func (slc ServerLogConfig) getLoggerName(host string) string {
if loggerName, ok := slc.LoggerNames[host]; ok {
tryHost := func(key string) (string, bool) {
// first try exact match
if loggerName, ok := slc.LoggerNames[key]; ok {
return loggerName, ok
}
// strip port and try again (i.e. Host header of "example.com:1234" should
// match "example.com" if there is no "example.com:1234" in the map)
hostOnly, _, err := net.SplitHostPort(key)
if err != nil {
return "", false
}
loggerName, ok := slc.LoggerNames[hostOnly]
return loggerName, ok
}

// try the exact hostname first
if loggerName, ok := tryHost(host); ok {
return loggerName
}

// Try matching wildcard domains if other non-specific loggers exist
// try matching wildcard domains if other non-specific loggers exist
labels := strings.Split(host, ".")
for i := range labels {
if labels[i] == "" {
continue
}
labels[i] = "*"
wildcardHost := strings.Join(labels, ".")
if loggerName, ok := slc.LoggerNames[wildcardHost]; ok {
if loggerName, ok := tryHost(wildcardHost); ok {
return loggerName
}
}
Expand Down

0 comments on commit 21c00a3

Please sign in to comment.