From c79a52ef87315d142b680062611c8f3a29dff090 Mon Sep 17 00:00:00 2001 From: Geno Date: Thu, 30 Mar 2017 14:49:14 +0200 Subject: [PATCH] [TASK] add new logging --- cmd/rezension/main.go | 5 ++--- http/status.go | 2 ++ lib/log.go | 33 +++++++++++++++++++++++++++++++++ lib/log_test.go | 23 +++++++++++++++++++++++ 4 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 lib/log.go create mode 100644 lib/log_test.go diff --git a/cmd/rezension/main.go b/cmd/rezension/main.go index 84785b2..7ede228 100644 --- a/cmd/rezension/main.go +++ b/cmd/rezension/main.go @@ -11,6 +11,7 @@ import ( goji "goji.io" http_api "github.com/genofire/hs_master-kss-monolith/http" + "github.com/genofire/hs_master-kss-monolith/lib" "github.com/genofire/hs_master-kss-monolith/models" ) @@ -28,9 +29,7 @@ func main() { // load config config = models.ReadConfigFile(configFile) - if !timestamps { - log.SetFlags(0) - } + lib.LogTimestamp(timestamps) log.Println("Starting rezension monolith") diff --git a/http/status.go b/http/status.go index 0d55b47..3d87239 100644 --- a/http/status.go +++ b/http/status.go @@ -7,5 +7,7 @@ import ( ) func statusHandler(w http.ResponseWriter, r *http.Request) { + log := lib.LogHTTP(r) lib.Write(w, "running") + log.Info("show status") } diff --git a/lib/log.go b/lib/log.go new file mode 100644 index 0000000..99424eb --- /dev/null +++ b/lib/log.go @@ -0,0 +1,33 @@ +package lib + +import ( + "log" + "net/http" + + logger "github.com/Sirupsen/logrus" +) + +var Log *logger.Logger + +func init(){ + Log = logger.New() + log.SetOutput(Log.Writer()) +} + +func LogTimestamp(value bool) { + logger.SetFormatter(&logger.TextFormatter{ + DisableTimestamp: value, + }) +} +// LogHTTP to add information of a httprequest to log +func LogHTTP(r *http.Request) *logger.Entry { + ip := r.Header.Get("X-Forwarded-For") + if len(ip) <= 1 { + ip = r.RemoteAddr + } + return Log.WithFields(logger.Fields{ + "remote": ip, + "method": r.Method, + "url": r.URL.RequestURI(), + }) +} diff --git a/lib/log_test.go b/lib/log_test.go new file mode 100644 index 0000000..3cb2baf --- /dev/null +++ b/lib/log_test.go @@ -0,0 +1,23 @@ +package lib + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLog(t *testing.T) { + assertion := assert.New(t) + + // No values check, just if it crashed or not + LogTimestamp(false) + + req, _ := http.NewRequest("GET", "https://google.com/lola/duda?q=wasd", nil) + log := LogHTTP(req) + _, ok := log.Data["remote"] + + assertion.NotNil(ok, "remote address not set in logger") + assertion.Equal("GET", log.Data["method"], "method not set in logger") + assertion.Equal("/lola/duda?q=wasd", log.Data["url"], "path not set in logger") +}