genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0

[TASK] add new logging

This commit is contained in:
Geno 2017-03-30 14:49:14 +02:00 committed by GitHub
parent 0a81ae70d4
commit c79a52ef87
4 changed files with 60 additions and 3 deletions

View File

@ -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")

View File

@ -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")
}

33
lib/log.go Normal file
View File

@ -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(),
})
}

23
lib/log_test.go Normal file
View File

@ -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")
}