Skip to content

Instantly share code, notes, and snippets.

@novemberde
Created March 1, 2020 14:46
Show Gist options
  • Save novemberde/1ad3cf003057fe306e96173af93c47cb to your computer and use it in GitHub Desktop.
Save novemberde/1ad3cf003057fe306e96173af93c47cb to your computer and use it in GitHub Desktop.
golang-chi-zerolog
type logFormatter struct{}
type logEntry struct {
userAgent string
method string
addr string
path string
}
func (l logFormatter) NewLogEntry(r *http.Request) middleware.LogEntry {
le := logEntry{
userAgent: r.Header.Get("user-agent"),
method: r.Method,
addr: r.RemoteAddr,
path: r.URL.Path,
}
return le
}
func (l logEntry) Write(status, bytes int, elapsed time.Duration) {
if strings.HasPrefix(l.path, "/health_check") {
return
}
var e *zerolog.Event
e.Str("ua", l.userAgent).
Str("method", l.method).
Str("addr", l.addr).
Str("path", l.path).
Int("status", status).
Int("in", bytes).
Dur("dur", elapsed).
Send()
}
func (l logEntry) Panic(v interface{}, stack []byte) {
fmt.Println("panic", v)
}
func chiLogger(next http.Handler) http.Handler {
return middleware.RequestLogger(logFormatter{})(next)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment