git » gofer » commit 7fa77bf

Use event tracing to log http server-level errors

author Alberto Bertogli
2020-04-26 03:11:02 UTC
committer Alberto Bertogli
2020-04-26 09:21:50 UTC
parent 6b0c6301bc723a784f748266474e29bc1c8c9cf9

Use event tracing to log http server-level errors

proxy/http.go +5 -0
trace/trace.go +14 -0

diff --git a/proxy/http.go b/proxy/http.go
index 9e29b8e..260ca80 100644
--- a/proxy/http.go
+++ b/proxy/http.go
@@ -2,6 +2,7 @@ package proxy
 
 import (
 	"crypto/tls"
+	golog "log"
 	"net/http"
 	"net/http/httputil"
 	"net/url"
@@ -16,11 +17,15 @@ import (
 )
 
 func httpServer(conf config.HTTP) *http.Server {
+	ev := trace.NewEventLog("httpserver", conf.Addr)
+
 	srv := &http.Server{
 		Addr: conf.Addr,
 
 		ReadTimeout:  30 * time.Second,
 		WriteTimeout: 30 * time.Second,
+
+		ErrorLog: golog.New(ev, "", golog.Lshortfile),
 	}
 
 	// Load route table.
diff --git a/trace/trace.go b/trace/trace.go
index aa9d5c9..8699778 100644
--- a/trace/trace.go
+++ b/trace/trace.go
@@ -5,6 +5,7 @@ import (
 	"context"
 	"fmt"
 	"strconv"
+	"strings"
 
 	"blitiri.com.ar/go/log"
 
@@ -124,6 +125,19 @@ func (e *EventLog) Errorf(format string, a ...interface{}) error {
 	return err
 }
 
+// Write so EventLog implements io.Writer, which means it can be used as
+// output for log.Logger.
+func (e *EventLog) Write(p []byte) (n int, err error) {
+	lines := strings.Split(string(p), "\n")
+	for _, line := range lines {
+		if strings.TrimSpace(line) == "" {
+			continue
+		}
+		e.Printf("%s", line)
+	}
+	return len(p), nil
+}
+
 func quote(s string) string {
 	qs := strconv.Quote(s)
 	return qs[1 : len(qs)-1]