Skip to content

Commit

Permalink
Add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
rumyantseva committed May 22, 2017
2 parents cf46732 + 5b4bc76 commit c9df240
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ You can try any other router.
For example, one of the most popular solutions is [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter).

Don't forget to check if tests are still green (`go test -v`) and change them if it is necessary.

## Step 05. Add logger

Add logger ([Sirupsen/logrus](https://github.com/Sirupsen/logrus) is my favourite!) to log requests.
9 changes: 9 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@ import (
func home(c *router.Control) {
fmt.Fprintf(c.Writer, "Processing URL %s...", c.Request.URL.Path)
}

// logger provides a log of requests
func logger(c *router.Control) {
remoteAddr := c.Request.Header.Get("X-Forwarded-For")
if remoteAddr == "" {
remoteAddr = c.Request.RemoteAddr
}
log.Infof("%s %s %s", remoteAddr, c.Request.Method, c.Request.URL.Path)
}
40 changes: 40 additions & 0 deletions handlers_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
package main

import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/Sirupsen/logrus"
"github.com/takama/router"
)

// buffer is a special variable to save log messages
var buffer bytes.Buffer

func init() {
log.Out = &buffer
log.Formatter = &logrus.JSONFormatter{}
}

// TestHandler is the simplest test: check base (/) URL
func TestHandler(t *testing.T) {
r := router.New()
Expand Down Expand Up @@ -39,3 +50,32 @@ func TestHandler(t *testing.T) {
)
}
}

// TestLogger checks if logger handler works correctly
func TestLogger(t *testing.T) {
r := router.New()
r.Logger = logger

ts := httptest.NewServer(r)
defer ts.Close()

_, err := http.Get(ts.URL + "/")
if err != nil {
t.Fatal(err)
}

formated := struct {
Level string `json:"level"`
Msg string `json:"msg"`
Time string `json:"time"`
}{}
err = json.NewDecoder(&buffer).Decode(&formated)
if err != nil {
t.Fatal(err)
}

msgParts := strings.Split(formated.Msg, " ")
if len(msgParts) != 3 {
t.Fatalf("Wrong message was logged: %s", formated.Msg)
}
}
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package main

import (
"github.com/Sirupsen/logrus"
"github.com/takama/router"
)

var log = logrus.New()

// Run server: go build && step-by-step
// Try requests: curl http://127.0.0.1:8000/test
func main() {
r := router.New()
r.Logger = logger
r.GET("/", home)
r.Listen(":8000")
}

0 comments on commit c9df240

Please sign in to comment.