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

Commit

Permalink
Merge pull request #2 from kitabisa/feat/add-curl-log
Browse files Browse the repository at this point in the history
feat: added curl request and log improvement by using zerolog
  • Loading branch information
sswastioyono18 authored Oct 6, 2021
2 parents 065508d + 62b595e commit 1c98a1a
Show file tree
Hide file tree
Showing 4 changed files with 241 additions and 37 deletions.
58 changes: 22 additions & 36 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import (
"github.com/tidwall/gjson"
"io"
"io/ioutil"
"log"
"moul.io/http2curl"
"net/http"
"os"
"time"
)

Expand All @@ -20,20 +19,29 @@ type Client struct {
PrivateKey []byte
PublicKey []byte
LogLevel int
Logger *log.Logger
Logger Logger
SignatureEnabled bool
}

// NewClient : this function will always be called when the library is in use
func NewClient() Client {
logOption := LogOption{
Format: "text",
Level: "info",
TimestampFormat: "2006-01-02T15:04:05-0700",
CallerToggle: false,
}

logger := *NewLogger(logOption)

return Client{
// LogLevel is the logging level used by the Dana library
// 0: No logging
// 1: Errors only
// 2: Errors + informational (default)
// 3: Errors + informational + debug
LogLevel: 2,
Logger: log.New(os.Stderr, "", log.LstdFlags),
Logger: logger,
SignatureEnabled: true,
}
}
Expand All @@ -44,14 +52,9 @@ var httpClient = &http.Client{Timeout: defHTTPTimeout}

// NewRequest : send new request
func (c *Client) NewRequest(method string, fullPath string, headers map[string]string, body io.Reader) (*http.Request, error) {
logLevel := c.LogLevel
logger := c.Logger

req, err := http.NewRequest(method, fullPath, body)
if err != nil {
if logLevel > 0 {
logger.Println("Request creation failed: ", err)
}
c.Logger.Info("Request creation failed: %v ", err)
return nil, err
}

Expand All @@ -66,45 +69,28 @@ func (c *Client) NewRequest(method string, fullPath string, headers map[string]s

// ExecuteRequest : execute request
func (c *Client) ExecuteRequest(req *http.Request, v interface{}) error {
logLevel := c.LogLevel
logger := c.Logger

if logLevel > 1 {
logger.Println("Request ", req.Method, ": ", req.URL.Host, req.URL.Path)
}
c.Logger.Info("Start requesting: %v ", req.URL)

command, _ := http2curl.GetCurlCommand(req)
start := time.Now()
res, err := httpClient.Do(req)
if err != nil {
if logLevel > 0 {
logger.Println("Cannot send request: ", err)
}
c.Logger.Error("Request failed. Error : %v , Curl Request : %v", err, command)
return err
}
defer res.Body.Close()

if logLevel > 2 {
logger.Println("Completed in ", time.Since(start))
}

if err != nil {
if logLevel > 0 {
logger.Println("Request failed: ", err)
}
return err
}
c.Logger.Info("Completed in %v", time.Since(start))
c.Logger.Info("Curl Request: %v ", command)

resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
if logLevel > 0 {
logger.Println("Cannot read response body: ", err)
}
c.Logger.Error("Cannot read response body: %v ", err)
return err
}

if logLevel > 2 {
logger.Println("Dana response: ", string(resBody))
}
c.Logger.Info("DANA HTTP status response : %d", res.StatusCode)
c.Logger.Info("DANA response body : %s", string(resBody))

if v != nil && res.StatusCode == 200 {
if err = json.Unmarshal(resBody, v); err != nil {
Expand All @@ -115,7 +101,7 @@ func (c *Client) ExecuteRequest(req *http.Request, v interface{}) error {
response := gjson.Get(string(resBody), "response")
signature := gjson.Get(string(resBody), "signature")

err := verifySignature(response.String(), signature.String(), c.PublicKey)
err = verifySignature(response.String(), signature.String(), c.PublicKey)
if err != nil {
return err
}
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ require (
github.com/BurntSushi/toml v0.3.1
github.com/google/uuid v1.1.1
github.com/mitchellh/mapstructure v1.1.2
github.com/rs/zerolog v1.25.0
github.com/stretchr/testify v1.4.0
github.com/tidwall/gjson v1.3.2
moul.io/http2curl v1.0.0
)
31 changes: 30 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.25.0 h1:Rj7XygbUHKUlDPcVdoLyR91fJBsduXj5fRxyqIQj/II=
github.com/rs/zerolog v1.25.0/go.mod h1:7KHcEGe0QZPOm2IE4Kpb5rTh6n1h2hIgS5OOnu1rUaI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
Expand All @@ -18,6 +23,30 @@ github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
187 changes: 187 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package dana

import (
"context"
"fmt"
"os"
"runtime"
"strings"
"time"

"github.com/rs/zerolog"
)

const (
APPLICATION_NAME = "sangu-dana"
LOG_KEY_REQ_ID = "req_id"
LOG_KEY_METHOD = "method"
LOG_KEY_CALLER = "caller"
LOG_LEVEL_TRACE = "trace"
LOG_LEVEL_DEBUG = "debug"
LOG_LEVEL_INFO = "info"
LOG_LEVEL_WARN = "warn"
LOG_LEVEL_ERROR = "error"
)

type LogOption struct {
Format string
Level string
TimestampFormat string
CallerToggle bool
Pretty bool
}

type Logger struct {
logger *zerolog.Logger
event *zerolog.Event
useCaller bool
ctx context.Context
method string
}

func NewLogger(option LogOption) *Logger {
setLogLevel(option.Level)
setTimeFormat(option.TimestampFormat)

var logger zerolog.Logger

if option.Pretty {
logger = logger.Output(zerolog.ConsoleWriter{Out: os.Stderr, FormatTimestamp: func(i interface{}) string { return time.Now().Format(option.TimestampFormat) }})
} else {
logger = zerolog.New(os.Stderr).With().Timestamp().Logger()
}

return &Logger{
logger: &logger,
useCaller: option.CallerToggle,
}
}

func (l *Logger) Ctx(ctx context.Context) *Logger {
l.ctx = ctx
return l
}

func (l *Logger) Method(name string) *Logger {
l.method = name
return l
}

func (l *Logger) Str(key string, val string) *Logger {
l.event = l.event.Str(key, val)
return l
}

func (l *Logger) Trace(format string, v ...interface{}) {
l.logEvent(LOG_LEVEL_TRACE).withCtx().withCaller().withMethod().msgf(format, v...)
}

func (l *Logger) Debug(format string, v ...interface{}) {
l.logEvent(LOG_LEVEL_DEBUG).withCtx().withCaller().withMethod().msgf(format, v...)
}

func (l *Logger) Info(format string, v ...interface{}) {
l.logEvent(LOG_LEVEL_INFO).withCtx().withMethod().msgf(format, v...)
}

func (l *Logger) Warn(format string, v ...interface{}) {
l.logEvent(LOG_LEVEL_WARN).withCtx().withCaller().withMethod().msgf(format, v...)
}

func (l *Logger) Error(format string, v ...interface{}) {
l.logEvent(LOG_LEVEL_ERROR).withCtx().withCaller().withMethod().msgf(format, v...)
}

func (l *Logger) msgf(format string, v ...interface{}) {
l.event.Msgf(format, v...)
}

func (l *Logger) withCtx() *Logger {
if l.ctx == nil {
return l
}

reqID, ok := l.ctx.Value(LOG_KEY_REQ_ID).(string)
if !ok {
return l
}

l.event = l.event.Str(LOG_KEY_REQ_ID, reqID)
return l
}

func (l *Logger) withMethod() *Logger {
if l.method == "" {
return l
}

l.event = l.event.Str(LOG_KEY_METHOD, l.method)
return l
}

func (l *Logger) withCaller() *Logger {
if !l.useCaller {
return l
}

skip := 2 // go back up to 2 stack before printing log to know the true caller
_, file, line, ok := runtime.Caller(skip)
if !ok {
return l
}

fileparts := strings.Split(file, APPLICATION_NAME)
shortname := fmt.Sprintf("%s%s", APPLICATION_NAME, fileparts[len(fileparts)-1])

l.event = l.event.Str(LOG_KEY_CALLER, fmt.Sprintf("%s:%d", shortname, line))
return l
}

func (l *Logger) logEvent(level string) *Logger {
switch level {
case LOG_LEVEL_TRACE:
l.event = l.logger.Trace()
return l
case LOG_LEVEL_DEBUG:
l.event = l.logger.Debug()
return l
case LOG_LEVEL_INFO:
l.event = l.logger.Info()
return l
case LOG_LEVEL_WARN:
l.event = l.logger.Warn()
return l
case LOG_LEVEL_ERROR:
l.event = l.logger.Error()
return l
default:
l.event = l.logger.Trace()
return l
}
}

func setLogLevel(level string) {
switch level {
case LOG_LEVEL_TRACE:
zerolog.SetGlobalLevel(zerolog.TraceLevel)
case LOG_LEVEL_DEBUG:
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case LOG_LEVEL_INFO:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case LOG_LEVEL_WARN:
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case LOG_LEVEL_ERROR:
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
default:
zerolog.SetGlobalLevel(zerolog.WarnLevel)
}
}

func setTimeFormat(format string) {
if format != "" {
zerolog.TimeFieldFormat = format
return
}

zerolog.TimeFieldFormat = "2006-01-02T15:04:05-0700"
}

0 comments on commit 1c98a1a

Please sign in to comment.