From 44f90870108d5cc77d22dd79b395ca43bc4a155f Mon Sep 17 00:00:00 2001 From: Martin Geno Date: Wed, 17 May 2017 14:58:28 +0200 Subject: [PATCH] [TASK] add log --- log/main.go | 32 ++++++++++++++++++++++++++++++++ log/main_test.go | 22 ++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 log/main.go create mode 100644 log/main_test.go diff --git a/log/main.go b/log/main.go new file mode 100644 index 0000000..6a4604f --- /dev/null +++ b/log/main.go @@ -0,0 +1,32 @@ +// Package that provides the functionality to start und initialize the logger +package log + +import ( + "log" + "net/http" + + logger "github.com/Sirupsen/logrus" +) + +// Current logger with it's configuration +var Log *logger.Logger + +// Function to initiate a new logger +func init() { + Log = logger.New() + // Enable fallback, if core logger + log.SetOutput(Log.Writer()) +} + +// Function to add the information of a http request to the log +func HTTP(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/log/main_test.go b/log/main_test.go new file mode 100644 index 0000000..a7fb705 --- /dev/null +++ b/log/main_test.go @@ -0,0 +1,22 @@ +// Package that provides the functionality to start und initialize the logger +package log + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" +) + +// Function to test the logging +func TestLog(t *testing.T) { + assertion := assert.New(t) + + req, _ := http.NewRequest("GET", "https://google.com/lola/duda?q=wasd", nil) + log := HTTP(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") +}