Created
March 1, 2020 14:46
-
-
Save novemberde/1ad3cf003057fe306e96173af93c47cb to your computer and use it in GitHub Desktop.
golang-chi-zerolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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