Skip to content

Commit

Permalink
feat: init logging middleware on server mode
Browse files Browse the repository at this point in the history
Signed-off-by: Matthis Holleville <matthish29@gmail.com>
  • Loading branch information
matthisholleville committed Apr 16, 2023
1 parent 64f359c commit 6742410
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 7 deletions.
77 changes: 77 additions & 0 deletions pkg/server/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package server

import (
"bytes"
"net/http"
"time"

"go.uber.org/zap"
)

type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
buf *bytes.Buffer
}

func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{
w,
http.StatusOK,
&bytes.Buffer{},
}
}

func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}

func (lrw *loggingResponseWriter) Write(b []byte) (int, error) {
return lrw.buf.Write(b)
}

func (lrw *loggingResponseWriter) Flush() {
if f, ok := lrw.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
lrw.ResponseWriter.Write(lrw.buf.Bytes())
}

func logRequest(logger *zap.Logger, fields []zap.Field, statusCode int, message string) {
if statusCode >= 400 {
logger.Error(message, fields...)
} else {
logger.Info("request completed", fields...)
}
}

func loggingMiddleware(next http.Handler) http.Handler {
config := zap.NewProductionConfig()
config.DisableCaller = true
logger, err := config.Build()
if err != nil {
panic(err)
}
defer logger.Sync()

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lrw := NewLoggingResponseWriter(w)
start := time.Now()
defer func() {
duration := time.Since(start).Milliseconds()
fields := []zap.Field{
zap.Int64("duration_ms", duration),
zap.String("method", r.Method),
zap.String("remote_addr", r.RemoteAddr),
zap.Int("status_code", lrw.statusCode),
zap.String("url", r.URL.Path),
}
logRequest(logger, fields, lrw.statusCode, lrw.buf.String())
}()

next.ServeHTTP(lrw, r)

lrw.Flush()
})
}
17 changes: 10 additions & 7 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,42 +51,45 @@ func (s *Config) analyzeHandler(w http.ResponseWriter, r *http.Request) {
config, err := analysis.NewAnalysis(s.Backend, language, []string{}, namespace, nocache, explain)
if err != nil {
health.Failure++
fmt.Fprintf(w, err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

err = config.RunAnalysis()
if err != nil {
color.Red("Error: %v", err)
health.Failure++
fmt.Fprintf(w, err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

if explain {
err := config.GetAIResults(s.Output, anonymize)
if err != nil {
color.Red("Error: %v", err)
health.Failure++
fmt.Fprintf(w, err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

out, err := config.PrintOutput(s.Output)
if err != nil {
color.Red("Error: %v", err)
health.Failure++
fmt.Fprintf(w, err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

health.Success++
fmt.Fprintf(w, string(out))
}

func (s *Config) Serve() error {
handler := loggingMiddleware(http.DefaultServeMux)
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/analyze", s.analyzeHandler)
http.HandleFunc("/healthz", s.healthzHandler)
color.Green("Starting server on port %s", s.Port)
err := http.ListenAndServe(":"+s.Port, nil)
err := http.ListenAndServe(":"+s.Port, handler)
if err != nil {
fmt.Printf("error starting server: %s\n", err)
return err
Expand Down

0 comments on commit 6742410

Please sign in to comment.