1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2025-05-29 01:45:35 +02:00

Logging WIP

This commit is contained in:
binwiederhier 2023-02-04 21:26:01 -05:00
parent a6641980c2
commit 5d6051c490
11 changed files with 108 additions and 124 deletions
server

View file

@ -1,15 +1,12 @@
package server
import (
"fmt"
"github.com/emersion/go-smtp"
"heckel.io/ntfy/log"
"heckel.io/ntfy/util"
"io"
"net/http"
"net/netip"
"strings"
"unicode/utf8"
)
func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
@ -48,90 +45,6 @@ func readQueryParam(r *http.Request, names ...string) string {
return ""
}
func logr(r *http.Request) *log.Event {
return log.Fields(logFieldsHTTP(r))
}
func logv(v *visitor) *log.Event {
return log.Context(v)
}
func logvr(v *visitor, r *http.Request) *log.Event {
return logv(v).Fields(logFieldsHTTP(r))
}
func logvrm(v *visitor, r *http.Request, m *message) *log.Event {
return logvr(v, r).Context(m)
}
func logvm(v *visitor, m *message) *log.Event {
return logv(v).Context(m)
}
func logem(state *smtp.ConnectionState) *log.Event {
return log.
Tag(tagSMTP).
Fields(map[string]any{
"smtp_hostname": state.Hostname,
"smtp_remote_addr": state.RemoteAddr.String(),
})
}
func logFieldsHTTP(r *http.Request) map[string]any {
requestURI := r.RequestURI
if requestURI == "" {
requestURI = r.URL.Path
}
return map[string]any{
"http_method": r.Method,
"http_path": requestURI,
}
}
func logHTTPPrefix(v *visitor, r *http.Request) string {
requestURI := r.RequestURI
if requestURI == "" {
requestURI = r.URL.Path
}
return fmt.Sprintf("HTTP %s %s %s", v.String(), r.Method, requestURI)
}
func logStripePrefix(customerID, subscriptionID string) string {
if subscriptionID != "" {
return fmt.Sprintf("STRIPE %s/%s", customerID, subscriptionID)
}
return fmt.Sprintf("STRIPE %s", customerID)
}
func renderHTTPRequest(r *http.Request) string {
peekLimit := 4096
lines := fmt.Sprintf("%s %s %s\n", r.Method, r.URL.RequestURI(), r.Proto)
for key, values := range r.Header {
for _, value := range values {
lines += fmt.Sprintf("%s: %s\n", key, value)
}
}
lines += "\n"
body, err := util.Peek(r.Body, peekLimit)
if err != nil {
lines = fmt.Sprintf("(could not read body: %s)\n", err.Error())
} else if utf8.Valid(body.PeekedBytes) {
lines += string(body.PeekedBytes)
if body.LimitReached {
lines += fmt.Sprintf(" ... (peeked %d bytes)", peekLimit)
}
lines += "\n"
} else {
if body.LimitReached {
lines += fmt.Sprintf("(peeked bytes not UTF-8, peek limit of %d bytes reached, hex: %x ...)\n", peekLimit, body.PeekedBytes)
} else {
lines += fmt.Sprintf("(peeked bytes not UTF-8, %d bytes, hex: %x)\n", len(body.PeekedBytes), body.PeekedBytes)
}
}
r.Body = body // Important: Reset body, so it can be re-read
return strings.TrimSpace(lines)
}
func extractIPAddress(r *http.Request, behindProxy bool) netip.Addr {
remoteAddr := r.RemoteAddr
addrPort, err := netip.ParseAddrPort(remoteAddr)