Skip to content
This repository has been archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
Merge pull request #71 from openfresh/feature/fix-remote-addr
Browse files Browse the repository at this point in the history
remove port number from remote-addr
  • Loading branch information
stormcat24 authored Dec 15, 2017
2 parents 54b7b1b + d65a92e commit e0ddc50
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ SERIAL_PACKAGES= \
manager \
pubsub \
server \
subscriber
subscriber \
log
TARGET_SERIAL_PACKAGES=$(addprefix test-,$(SERIAL_PACKAGES))

install-go:
Expand Down
16 changes: 15 additions & 1 deletion log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io/ioutil"
"net/http"
"os"
"regexp"
"time"

"google.golang.org/grpc"
Expand All @@ -16,6 +17,10 @@ import (
"go.uber.org/zap/zapcore"
)

var (
regexIPAddress = regexp.MustCompile(`^(.+):\d{4,5}$`)
)

func NewLogger(config config.Log) (*zap.Logger, error) {
var writer io.Writer
switch config.Out {
Expand Down Expand Up @@ -67,13 +72,22 @@ func HTTPRequestToLogFields(r *http.Request) []zapcore.Field {
if addr := r.Header.Get("X-Forwarded-For"); addr != "" {
remoteAddr = addr
}

return []zapcore.Field{
zap.String("user-agent", r.UserAgent()),
zap.String("referer", r.Referer()),
zap.Int64("content-length", r.ContentLength),
zap.String("host", r.Host),
zap.String("method", r.Method),
zap.String("remote-addr", remoteAddr),
zap.String("remote-addr", removePort(remoteAddr)),
zap.String("time", time.Now().Format(time.RFC3339Nano)),
}
}

func removePort(remoteAddr string) string {
tokens := regexIPAddress.FindStringSubmatch(remoteAddr)
if len(tokens) == 2 {
return tokens[1]
}
return remoteAddr
}
21 changes: 21 additions & 0 deletions log/log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package log

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestRemovePortV4(t *testing.T) {

assert := assert.New(t)
actual := removePort("127.0.0.1:60000")
assert.Equal("127.0.0.1", actual)
}

func TestRemovePortV6(t *testing.T) {

assert := assert.New(t)
actual := removePort("[::1]:60000")
assert.Equal("[::1]", actual)
}

0 comments on commit e0ddc50

Please sign in to comment.