diff --git a/Makefile b/Makefile index dae01fe..b40c8ee 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,8 @@ SERIAL_PACKAGES= \ manager \ pubsub \ server \ - subscriber + subscriber \ + log TARGET_SERIAL_PACKAGES=$(addprefix test-,$(SERIAL_PACKAGES)) install-go: diff --git a/log/log.go b/log/log.go index ea70c5a..4065e48 100644 --- a/log/log.go +++ b/log/log.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "net/http" "os" + "regexp" "time" "google.golang.org/grpc" @@ -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 { @@ -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 +} diff --git a/log/log_test.go b/log/log_test.go new file mode 100644 index 0000000..6753dbd --- /dev/null +++ b/log/log_test.go @@ -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) +}