Initial Commit
This commit is contained in:
25
internal/logging/badger.go
Normal file
25
internal/logging/badger.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type BadgerLogger struct{}
|
||||
|
||||
func (BadgerLogger) Infof(format string, v ...interface{}) {
|
||||
log.Info().Msgf(strings.TrimSuffix(format, "\n"), v...)
|
||||
}
|
||||
|
||||
func (BadgerLogger) Warningf(format string, v ...interface{}) {
|
||||
log.Error().Msgf(strings.TrimSuffix(format, "\n"), v...)
|
||||
}
|
||||
|
||||
func (BadgerLogger) Debugf(format string, v ...interface{}) {
|
||||
log.Debug().Msgf(strings.TrimSuffix(format, "\n"), v...)
|
||||
}
|
||||
|
||||
func (BadgerLogger) Errorf(format string, v ...interface{}) {
|
||||
log.Error().Msgf(strings.TrimSuffix(format, "\n"), v...)
|
||||
}
|
||||
50
internal/logging/chi.go
Normal file
50
internal/logging/chi.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func ChiLogger(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
|
||||
t1 := time.Now()
|
||||
defer func() {
|
||||
t2 := time.Now()
|
||||
|
||||
// Recover and record stack traces in case of a panic
|
||||
if rec := recover(); rec != nil {
|
||||
log.Error().
|
||||
Str("method", r.Method).
|
||||
Str("path", r.URL.Path).
|
||||
Msgf("Panic during request")
|
||||
middleware.PrintPrettyStack(rec)
|
||||
http.Error(ww, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
remoteIP, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
|
||||
var event = log.Info()
|
||||
if ww.Status() != 200 {
|
||||
event = log.Error()
|
||||
}
|
||||
// log end request
|
||||
event.Fields(map[string]interface{}{
|
||||
"remote_ip": remoteIP,
|
||||
"proto": r.Proto,
|
||||
"user_agent": r.Header.Get("User-Agent"),
|
||||
"status": ww.Status(),
|
||||
"latency_ms": float64(t2.Sub(t1).Nanoseconds()) / 1000000.0,
|
||||
}).Msgf("%s %s", r.Method, r.URL.Path)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(ww, r)
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
Reference in New Issue
Block a user