From cd2ed76903b51c790e64374968cbc65b09323cae Mon Sep 17 00:00:00 2001 From: m5r Date: Sun, 28 Jul 2024 12:15:59 +0200 Subject: [PATCH] smarter structured logs --- http/server.go | 6 +++++- xip/xip.go | 18 ++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/http/server.go b/http/server.go index 9e6cc46..5bf56ff 100644 --- a/http/server.go +++ b/http/server.go @@ -20,7 +20,11 @@ func loggingMiddleware(w http.ResponseWriter, r *http.Request, next http.Handler start := time.Now() next(w, r) response := w.(negroni.ResponseWriter) - utils.Logger.Debug().Str("FLY_REGION", flyRegion).Msgf("%s %s %d %s", r.Method, r.URL.Path, response.Status(), time.Since(start)) + logEvent := utils.Logger.Debug() + if flyRegion != "" { + logEvent.Str("FLY_REGION", flyRegion) + } + logEvent.Msgf("%s %s %d %s", r.Method, r.URL.Path, response.Status(), time.Since(start)) } func newHttpMux() http.Handler { diff --git a/xip/xip.go b/xip/xip.go index a17fc0d..efa88a8 100644 --- a/xip/xip.go +++ b/xip/xip.go @@ -18,9 +18,10 @@ type Xip struct { } var ( - flyRegion = os.Getenv("FLY_REGION") - dottedIpV4Regex = regexp.MustCompile(`(?:^|(?:[\w\d])+\.)(((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4})($|[.-])`) - dashedIpV4Regex = regexp.MustCompile(`(?:^|(?:[\w\d])+\.)(((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\-?\b){4})($|[.-])`) + flyRegion = os.Getenv("FLY_REGION") + dottedIpV4Regex = regexp.MustCompile(`(?:^|(?:[\w\d])+\.)(((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4})($|[.-])`) + dashedIpV4Regex = regexp.MustCompile(`(?:^|(?:[\w\d])+\.)(((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\-?\b){4})($|[.-])`) + anyWhitespaceRegex = regexp.MustCompile(`\s`) ) func (xip *Xip) SetTXTRecord(fqdn string, value string) { @@ -333,10 +334,15 @@ func (xip *Xip) handleDnsRequest(response dns.ResponseWriter, request *dns.Msg) message.MsgHdr.Rcode = dns.RcodeRefused } - logEvent := utils.Logger.Debug().Str("FLY_REGION", flyRegion).Str("question", request.Question[0].String()) - re := regexp.MustCompile(`\s`) + question := anyWhitespaceRegex.ReplaceAllString(request.Question[0].String(), " ") + logEvent := utils.Logger.Debug().Str("question", question) + if flyRegion != "" { + logEvent.Str("FLY_REGION", flyRegion) + } for i, answer := range message.Answer { - logEvent.Str(fmt.Sprintf("answers[%d]", i), re.ReplaceAllString(answer.String(), " ")) + key := fmt.Sprintf("answers[%d]", i) + value := anyWhitespaceRegex.ReplaceAllString(answer.String(), " ") + logEvent.Str(key, value) } logEvent.Msg("resolved")