Skip to content

Adding IP Addresses in log entries #212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package middleware

import (
"log"
"net"
"time"

"github.com/labstack/echo"
Expand All @@ -11,6 +12,15 @@ import (
func Logger() echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {

remoteAddr := c.Request().RemoteAddr
if realIP := c.Request().Header.Get("X-Real-IP"); realIP != "" {
remoteAddr = realIP
}
if realIP := c.Request().Header.Get("X-Forwarded-For"); realIP != "" {
remoteAddr = realIP
}

start := time.Now()
if err := h(c); err != nil {
c.Error(err)
Expand All @@ -34,7 +44,9 @@ func Logger() echo.MiddlewareFunc {
code = color.Cyan(n)
}

log.Printf("%s %s %s %s %d", method, path, code, stop.Sub(start), size)
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)

log.Printf("%s %s %s %s %s %d", remoteAddr, method, path, code, stop.Sub(start), size)
return nil
}
}
Expand Down
18 changes: 17 additions & 1 deletion middleware/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,28 @@ package middleware

import (
"errors"
"github.com/labstack/echo"
"net/http"
"net/http/httptest"
"testing"

"github.com/labstack/echo"
)

func TestRealIPHeader(t *testing.T) {
e := echo.New()
req, _ := http.NewRequest(echo.GET, "/", nil)
req.Header.Add("X-Real-IP", "127.0.0.1")
req.Header.Add("X-Forwarded-For", "127.0.0.1")
rec := httptest.NewRecorder()
c := echo.NewContext(req, echo.NewResponse(rec), e)

// Status 2xx
h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
Logger()(h)(c)
}

func TestLogger(t *testing.T) {
e := echo.New()
req, _ := http.NewRequest(echo.GET, "/", nil)
Expand Down