Skip to content

Commit

Permalink
feat: drop logrus
Browse files Browse the repository at this point in the history
  • Loading branch information
morlay committed Mar 9, 2021
1 parent ab74498 commit ce30f84
Show file tree
Hide file tree
Showing 35 changed files with 193 additions and 196 deletions.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ VERSION = v$(shell cat .version)
COMMIT_SHA ?= $(shell git describe --always)-devel
GOTEST = go test -v -race

fmt:
goimports -l -w .
gofmt -l -w .

test:
GODEBUG=x509ignoreCN=0 $(GOTEST) ./...

Expand Down
6 changes: 3 additions & 3 deletions __examples__/downstream/client_demo/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type ClientDemo interface {
FormMultipartWithFiles(req *FormMultipartWithFiles, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error)
FormURLEncoded(req *FormURLEncoded, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error)
GetByID(req *GetByID, metas ...github_com_go_courier_courier.Metadata) (*Data, github_com_go_courier_courier.Metadata, error)
HealthCheck(metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error)
HealthCheck(req *HealthCheck, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error)
Proxy(metas ...github_com_go_courier_courier.Metadata) (*IpInfo, github_com_go_courier_courier.Metadata, error)
ProxyV2(metas ...github_com_go_courier_courier.Metadata) (*IpInfo, github_com_go_courier_courier.Metadata, error)
Redirect(metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error)
Expand Down Expand Up @@ -79,8 +79,8 @@ func (c *ClientDemoStruct) GetByID(req *GetByID, metas ...github_com_go_courier_
return req.InvokeContext(c.Context(), c.Client, metas...)
}

func (c *ClientDemoStruct) HealthCheck(metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) {
return (&HealthCheck{}).InvokeContext(c.Context(), c.Client, metas...)
func (c *ClientDemoStruct) HealthCheck(req *HealthCheck, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) {
return req.InvokeContext(c.Context(), c.Client, metas...)
}

func (c *ClientDemoStruct) Proxy(metas ...github_com_go_courier_courier.Metadata) (*IpInfo, github_com_go_courier_courier.Metadata, error) {
Expand Down
1 change: 1 addition & 0 deletions __examples__/downstream/client_demo/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ func (req *GetByID) Invoke(c github_com_go_courier_courier.Client, metas ...gith
}

type HealthCheck struct {
PullPolicy GithubComGoCourierHttptransportExamplesServerPkgTypesPullPolicy `in:"query" name:"pullPolicy,omitempty"`
}

func (HealthCheck) Path() string {
Expand Down
2 changes: 2 additions & 0 deletions __examples__/downstream/client_demo/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ type Data struct {

type GithubComGoCourierHttptransportExamplesServerPkgTypesProtocol = github_com_go_courier_httptransport_examples_server_pkg_types.Protocol

type GithubComGoCourierHttptransportExamplesServerPkgTypesPullPolicy = github_com_go_courier_httptransport_examples_server_pkg_types.PullPolicy

type GithubComGoCourierHttptransportHttpxAttachment = github_com_go_courier_httptransport_httpx.Attachment

type GithubComGoCourierHttptransportHttpxImagePNG = github_com_go_courier_httptransport_httpx.ImagePNG
Expand Down
4 changes: 2 additions & 2 deletions __examples__/server/cmd/app/routes/restful.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package routes

import (
"context"
"fmt"

"github.com/go-courier/courier"
"github.com/go-courier/httptransport/__examples__/server/pkg/errors"
"github.com/go-courier/httptransport/__examples__/server/pkg/types"
"github.com/go-courier/httptransport/httpx"
perrors "github.com/pkg/errors"

"github.com/go-courier/httptransport"
)
Expand Down Expand Up @@ -95,7 +95,7 @@ type UpdateByID struct {
}

func (req UpdateByID) Output(ctx context.Context) (interface{}, error) {
return nil, fmt.Errorf("something wrong")
return nil, perrors.Errorf("something wrong")
}

type DataProvider struct {
Expand Down
3 changes: 2 additions & 1 deletion __examples__/server/pkg/types/protocol__generated.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package types
import (
"bytes"
database_sql_driver "database/sql/driver"
"errors"

"github.com/pkg/errors"

github_com_go_courier_enumeration "github.com/go-courier/enumeration"
)
Expand Down
9 changes: 4 additions & 5 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package client

import (
"context"
"errors"
"fmt"
"io"
"mime"
Expand All @@ -12,16 +11,16 @@ import (
"reflect"
"time"

"github.com/pkg/errors"

"github.com/go-courier/courier"
"github.com/go-courier/httptransport"
"github.com/go-courier/httptransport/client/roundtrippers"
"github.com/go-courier/httptransport/httpx"
"github.com/go-courier/httptransport/transformers"
"github.com/go-courier/reflectx/typesutil"
"github.com/go-courier/statuserror"
"github.com/sirupsen/logrus"
"golang.org/x/net/http2"

"github.com/go-courier/httptransport"
)

type HttpTransport func(rt http.RoundTripper) http.RoundTripper
Expand All @@ -42,7 +41,7 @@ func (c *Client) SetDefaults() {
c.RequestTransformerMgr.SetDefaults()
}
if c.HttpTransports == nil {
c.HttpTransports = []HttpTransport{roundtrippers.NewLogRoundTripper(logrus.WithField("client", ""))}
c.HttpTransports = []HttpTransport{roundtrippers.NewLogRoundTripper()}
}
if c.NewError == nil {
c.NewError = func(resp *http.Response) error {
Expand Down
4 changes: 2 additions & 2 deletions client/generator/client_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package generator
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
Expand All @@ -15,6 +14,7 @@ import (
"github.com/fatih/color"
"github.com/go-courier/codegen"
"github.com/go-courier/oas"
"github.com/pkg/errors"
"golang.org/x/mod/modfile"
"golang.org/x/tools/go/packages"
)
Expand Down Expand Up @@ -55,7 +55,7 @@ type ClientGenerator struct {

func (g *ClientGenerator) Load() {
if g.URL == nil {
panic(fmt.Errorf("missing spec-url or file"))
panic(errors.Errorf("missing spec-url or file"))
}

if g.URL.Scheme == "file" {
Expand Down
28 changes: 15 additions & 13 deletions client/roundtrippers/log_round_tripper.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,44 @@ import (
"net/http"
"time"

"github.com/sirupsen/logrus"
"github.com/go-courier/logr"
"github.com/pkg/errors"
)

func NewLogRoundTripper(logger *logrus.Entry) func(roundTripper http.RoundTripper) http.RoundTripper {
func NewLogRoundTripper() func(roundTripper http.RoundTripper) http.RoundTripper {
return func(roundTripper http.RoundTripper) http.RoundTripper {
return &LogRoundTripper{
logger: logger,
nextRoundTripper: roundTripper,
}
}
}

type LogRoundTripper struct {
logger *logrus.Entry
nextRoundTripper http.RoundTripper
}

func (rt *LogRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
startedAt := time.Now()

resp, err := rt.nextRoundTripper.RoundTrip(req)
ctx, logger := logr.Start(req.Context(), "Request")
defer logger.End()

resp, err := rt.nextRoundTripper.RoundTrip(req.WithContext(ctx))

defer func() {
cost := time.Since(startedAt)

logger := rt.logger.WithContext(req.Context()).WithFields(logrus.Fields{
"cost": fmt.Sprintf("%0.3fms", float64(cost/time.Millisecond)),
"method": req.Method,
"url": req.URL.String(),
"metadata": req.Header,
})
logger := logger.WithValues(
"cost", fmt.Sprintf("%0.3fms", float64(cost/time.Millisecond)),
"method", req.Method,
"url", req.URL.String(),
"metadata", req.Header,
)

if err == nil {
logger.Infof("success")
logger.Info("success")
} else {
logger.Warnf("do http request failed %s", err)
logger.Warn(errors.Wrap(err, "http request failed"))
}
}()

Expand Down
5 changes: 1 addition & 4 deletions client/roundtrippers/log_round_tripper_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package roundtrippers

import (
"context"
"net/http"
"testing"

"github.com/sirupsen/logrus"

"github.com/go-courier/httptransport"
)

Expand All @@ -16,5 +13,5 @@ func TestLogRoundTripper(t *testing.T) {

req, _ := mgr.NewRequest(http.MethodGet, "https://github.com", nil)

_, _ = NewLogRoundTripper(logrus.WithContext(context.Background()))(http.DefaultTransport).RoundTrip(req)
_, _ = NewLogRoundTripper()(http.DefaultTransport).RoundTrip(req)
}
13 changes: 7 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/go-courier/codegen v1.1.2
github.com/go-courier/courier v1.4.1
github.com/go-courier/enumeration v1.3.0
github.com/go-courier/logr v0.0.0
github.com/go-courier/metax v1.2.1
github.com/go-courier/oas v1.2.1
github.com/go-courier/packagesx v1.0.2
Expand All @@ -18,11 +19,11 @@ require (
github.com/julienschmidt/httprouter v1.3.0
github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect
github.com/magefile/mage v1.11.0 // indirect
github.com/sirupsen/logrus v1.8.0
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.7.0
golang.org/x/mod v0.4.1 // indirect
golang.org/x/net v0.0.0-20210222171744-9060382bd457
golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 // indirect
golang.org/x/mod v0.4.1
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 // indirect
golang.org/x/text v0.3.5 // indirect
golang.org/x/tools v0.1.0 // indirect
)
golang.org/x/tools v0.1.0
)
46 changes: 21 additions & 25 deletions handlers/log_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@ import (
"strings"
"time"

"github.com/go-courier/logr"
"github.com/pkg/errors"

"github.com/go-courier/httptransport/httpx"
"github.com/go-courier/metax"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)

func LogHandler(logger *logrus.Entry) func(handler http.Handler) http.Handler {
func LogHandler() func(handler http.Handler) http.Handler {
return func(handler http.Handler) http.Handler {
return &loggerHandler{
logger: logger,
nextHandler: handler,
}
}
}

type loggerHandler struct {
logger *logrus.Entry
nextHandler http.Handler
}

Expand Down Expand Up @@ -69,42 +69,38 @@ func (h *loggerHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {

startAt := time.Now()

level, _ := logrus.ParseLevel(strings.ToLower(req.Header.Get("x-log-level")))
if level == logrus.PanicLevel {
level = h.logger.Logger.Level
}
logger := logr.FromContext(req.Context())

level, _ := logr.ParseLevel(strings.ToLower(req.Header.Get("x-log-level")))

defer func() {
duration := time.Since(startAt)

logger := h.logger.WithContext(metax.ContextWithMeta(req.Context(), metax.ParseMeta(loggerRw.Header().Get("X-Meta"))))

header := req.Header

fields := logrus.Fields{
"tag": "access",
"cost": fmt.Sprintf("%0.3fms", float64(duration/time.Millisecond)),
"remote_ip": httpx.ClientIP(req),
"method": req.Method,
"request_url": req.URL.String(),
"user_agent": header.Get(httpx.HeaderUserAgent),
fields := []interface{}{
"tag", "access",
"cost", fmt.Sprintf("%0.3fms", float64(duration/time.Millisecond)),
"remote_ip", httpx.ClientIP(req),
"method", req.Method,
"request_url", req.URL.String(),
"user_agent", header.Get(httpx.HeaderUserAgent),
"status", loggerRw.StatusCode,
}

fields["status"] = loggerRw.StatusCode

if loggerRw.ErrMsg.Len() > 0 {
if loggerRw.StatusCode >= http.StatusInternalServerError {
if level >= logrus.ErrorLevel {
logger.WithFields(fields).Error(loggerRw.ErrMsg.String())
if level >= logr.ErrorLevel {
logger.WithValues(fields).Error(errors.New(loggerRw.ErrMsg.String()))
}
} else {
if level >= logrus.WarnLevel {
logger.WithFields(fields).Warn(loggerRw.ErrMsg.String())
if level >= logr.WarnLevel {
logger.WithValues(fields).Warn(errors.New(loggerRw.ErrMsg.String()))
}
}
} else {
if level >= logrus.InfoLevel {
logger.WithFields(fields).Info()
if level >= logr.InfoLevel {
logger.WithValues(fields).Info("")
}
}
}()
Expand Down
9 changes: 5 additions & 4 deletions handlers/log_handler_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package handlers

import (
"context"
"net/http"
"time"

"github.com/go-courier/httptransport/testify"
"github.com/sirupsen/logrus"
"github.com/go-courier/logr"
)

func ExampleLogHandler() {
logrus.SetLevel(logrus.DebugLevel)
ctx := logr.WithLogger(context.Background(), logr.StdLogger())

var handle http.HandlerFunc = func(rw http.ResponseWriter, req *http.Request) {
time.Sleep(20 * time.Millisecond)
Expand All @@ -29,10 +30,10 @@ func ExampleLogHandler() {
}
}

handler := LogHandler(logrus.WithField("service", ""))(handle).(*loggerHandler)
handler := LogHandler()(handle).(*loggerHandler)

for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete, http.MethodPost} {
req, _ := http.NewRequest(method, "/", nil)
req, _ := http.NewRequestWithContext(ctx, method, "/", nil)
handler.ServeHTTP(testify.NewMockResponseWriter(), req)
}
// Output:
Expand Down
5 changes: 3 additions & 2 deletions http_route_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package httptransport

import (
"context"
"fmt"
"io"
"net/http"
"reflect"

"github.com/pkg/errors"

"github.com/go-courier/courier"
"github.com/go-courier/httptransport/httpx"
"github.com/go-courier/httptransport/transformers"
Expand All @@ -19,7 +20,7 @@ func NewHttpRouteHandler(serviceMeta *ServiceMeta, httpRoute *HttpRouteMeta, req
operatorFactories := httpRoute.OperatorFactoryWithRouteMetas

if len(operatorFactories) == 0 {
panic(fmt.Errorf("missing valid operator"))
panic(errors.Errorf("missing valid operator"))
}

requestTransformers := make([]*RequestTransformer, len(operatorFactories))
Expand Down
Loading

0 comments on commit ce30f84

Please sign in to comment.