Skip to content

Instantly share code, notes, and snippets.

@lfaoro
Created March 6, 2019 10:21
Show Gist options
  • Save lfaoro/c060e4975292426673d9267662fb5bf3 to your computer and use it in GitHub Desktop.
Save lfaoro/c060e4975292426673d9267662fb5bf3 to your computer and use it in GitHub Desktop.
logging handler
package httpLogger
import (
"log"
"net/http"
"os"
"strings"
"time"
"git.vlct.io/vaultex/vaultex/internal/realip"
)
type statusWriter struct {
http.ResponseWriter
status int
length int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
w.length = len(b)
return w.ResponseWriter.Write(b)
}
// WriteLog Logs the Http Status for a request into fileHandler and returns a httphandler function which is a wrapper to log the requests.
func WriteLog(handle http.Handler, fileHandler *os.File) http.HandlerFunc {
logger := log.New(fileHandler, "", 0)
return func(w http.ResponseWriter, r *http.Request) {
// Skip logging requests to /health
if strings.Contains(r.RequestURI, "/health") {
handle.ServeHTTP(w, r)
return
}
realIP := realip.From(r)
start := time.Now()
writer := statusWriter{w, 0, 0}
handle.ServeHTTP(&writer, r)
end := time.Now()
latency := end.Sub(start)
statusCode := writer.status
length := writer.length
if r.URL.RawQuery != "" {
logger.Printf("%v %s %s \"%s %s%s%s %s\" %d %d \"%s\" %v", end.Format("2006/01/02 15:04:05"),
r.Host, realIP, r.Method, r.URL.Path, "?", r.URL.RawQuery, r.Proto,
statusCode, length, r.Header.Get("User-Agent"), latency)
} else {
logger.Printf("%v %s %s \"%s %s %s\" %d %d \"%s\" %v", end.Format("2006/01/02 15:04:05"), r.Host,
realIP, r.Method, r.URL.Path, r.Proto, statusCode, length,
r.Header.Get("User-Agent"), latency)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment