Skip to content

Commit

Permalink
add a custom logger
Browse files Browse the repository at this point in the history
  • Loading branch information
silaselisha committed May 24, 2024
1 parent a60bdfb commit a67e518
Show file tree
Hide file tree
Showing 16 changed files with 74 additions and 26 deletions.
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.22.0

require (
github.com/google/uuid v1.4.0
github.com/rs/zerolog v1.33.0
github.com/spf13/viper v1.18.2
github.com/stretchr/testify v1.9.0
)
Expand All @@ -13,6 +14,8 @@ require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
Expand All @@ -26,7 +29,7 @@ require (
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.14.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
19 changes: 17 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
Expand All @@ -6,6 +7,7 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
Expand All @@ -18,15 +20,25 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
Expand Down Expand Up @@ -58,8 +70,11 @@ go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
10 changes: 8 additions & 2 deletions pkg/handler/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/silaselisha/go-daraja/pkg/internal/auth"
"github.com/silaselisha/go-daraja/pkg/internal/builder"
"github.com/silaselisha/go-daraja/pkg/internal/config"
logger "github.com/silaselisha/go-daraja/pkg/internal/log"
)

type DarajaAuth struct {
Expand All @@ -22,8 +23,7 @@ type DarajaAuth struct {
func ClientAuth(cfgs *config.Configs) (*DarajaAuth, error) {
client := &http.Client{}

fmt.Println(cfgs.MpesaEnvironment)

logger := logger.DarajaLogger(cfgs)
URL := fmt.Sprintf("%s/%s", builder.BaseUrlBuilder(cfgs.MpesaEnvironment), "oauth/v1/generate?grant_type=client_credentials")

req, err := http.NewRequest(http.MethodGet, URL, nil)
Expand All @@ -38,21 +38,27 @@ func ClientAuth(cfgs *config.Configs) (*DarajaAuth, error) {
res, err := client.Do(req)

if err != nil {
logger.Error().Msg(err.Error())
return nil, err
}

defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
if err == io.EOF {
logger.Error().Msg(err.Error())
return nil, err
}
logger.Error().Msg(err.Error())
return nil, err
}

var darajaAuth *DarajaAuth
if err := json.Unmarshal(body, &darajaAuth); err != nil {
logger.Error().Msg(err.Error())
return nil, err
}

logger.Warn().Msg(string(body))
return darajaAuth, nil
}
2 changes: 0 additions & 2 deletions pkg/handler/auth_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"testing"

"github.com/silaselisha/go-daraja/pkg/internal/config"
Expand All @@ -24,7 +23,6 @@ func TestAuth(t *testing.T) {
{
name: "200 OK Auth Request",
check: func(t *testing.T, response any, err error) {
fmt.Print(response)
res := response.(*DarajaAuth)
require.NotEmpty(t, res)
require.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/handler/business-buygoods.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@ func (cl *DarajaClient) BusinessBuyGoods(amount float64, username, shortCode, co
ResultURL: resultURL,
}

data, err := handlerHelper[B2BReqParams](payload, URL, http.MethodPost, cl.accessToken)
data, err := handlerHelper[B2BReqParams](cl.logger, payload, URL, http.MethodPost, cl.accessToken)
return data, err
}
2 changes: 0 additions & 2 deletions pkg/handler/business-buygoods_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -35,7 +34,6 @@ func TestBusinessBuyGoods(t *testing.T) {
amount: 239,
accountRefrence: "353353",
check: func(t *testing.T, data *DarajaResParams, err error) {
fmt.Printf("Business Buy Goods: %+v\n", data)
require.NoError(t, err)

require.Equal(t, "0", data.ResponseCode)
Expand Down
2 changes: 1 addition & 1 deletion pkg/handler/business-consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,5 @@ func (cl *DarajaClient) BusinessToConsumer(amount float64, txnType txnType, cust
SecurityCredential: securityCred,
}

return handlerHelper[B2CReqParams](payload, URL, http.MethodPost, cl.accessToken)
return handlerHelper[B2CReqParams](cl.logger, payload, URL, http.MethodPost, cl.accessToken)
}
2 changes: 0 additions & 2 deletions pkg/handler/business-consumer_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -27,7 +26,6 @@ func TestBusinessConsumer(t *testing.T) {
qeueuTimeURL: "https://mydomain.com/b2c/queue",
resultURL: "https://mydomain.com/b2c/result",
check: func(t *testing.T, data *DarajaResParams, err error) {
fmt.Printf("Business Consumer: %+v\n", data)
require.NoError(t, err)

require.Equal(t, "0", data.ResponseCode)
Expand Down
2 changes: 1 addition & 1 deletion pkg/handler/business-express.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@ func (cl *DarajaClient) BusinessExpressCheckout(paymentRef, callbackURL, partner
}

fmt.Printf("PAYLOAD: %+v\n", payload)
return handlerHelper(payload, URL, http.MethodPost, cl.accessToken)
return handlerHelper(cl.logger, payload, URL, http.MethodPost, cl.accessToken)
}
2 changes: 0 additions & 2 deletions pkg/handler/business-express_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -25,7 +24,6 @@ func TestBusinessExpress(t *testing.T) {
receiver: "174379",
amount: 10,
check: func(t *testing.T, data *DarajaResParams, err error) {
fmt.Printf("Business Express: %+v\n", data)
require.NoError(t, err)

require.Equal(t, "0", data.ResponseBody.Code)
Expand Down
2 changes: 1 addition & 1 deletion pkg/handler/customer-business.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ func (cl *DarajaClient) CustomerToBusiness(confirmationURL, validationURL string
ValidationURL: validationURL,
}

return handlerHelper[C2BReqParams](payload, URL, http.MethodPost, cl.accessToken)
return handlerHelper[C2BReqParams](cl.logger, payload, URL, http.MethodPost, cl.accessToken)
}
2 changes: 0 additions & 2 deletions pkg/handler/customer-business_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -21,7 +20,6 @@ func TestCustomerToBusiness(t *testing.T) {
validationURL: "https://mydomain.com/validation",
confirmationURL: "https://mydomain.com/confirmation",
check: func(t *testing.T, data *DarajaResParams, err error) {
fmt.Printf("Consumer Business: %+v\n", data)
require.NoError(t, err)

if data.ErrorCode == "500.003.1001" {
Expand Down
13 changes: 10 additions & 3 deletions pkg/handler/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@ package handler
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"

"github.com/rs/zerolog"
)

func handlerHelper[T B2BReqParams | B2CReqParams | C2BReqParams | ExpressReqParams | BExpressCheckoutParams](payload T, url, method, authToken string) (*DarajaResParams, error) {
func handlerHelper[T B2BReqParams | B2CReqParams | C2BReqParams | ExpressReqParams | BExpressCheckoutParams](logger zerolog.Logger, payload T, url, method, authToken string) (*DarajaResParams, error) {
buff, err := json.Marshal(&payload)
if err != nil {
logger.Error().Msg(err.Error())
return nil, err
}

req, err := http.NewRequest(method, url, bytes.NewBuffer(buff))
if err != nil {
logger.Error().Msg(err.Error())
return nil, err
}

Expand All @@ -26,23 +29,27 @@ func handlerHelper[T B2BReqParams | B2CReqParams | C2BReqParams | ExpressReqPara
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
logger.Error().Msg(err.Error())
return nil, err
}

defer func() {
if err := res.Body.Close(); err != nil {
logger.Error().Msg(err.Error())
log.Fatalf("failed to close response body %v\n", err)
}
}()

buff, err = io.ReadAll(res.Body)
if err != nil {
logger.Error().Msg(err.Error())
return nil, err
}

fmt.Printf("Bytes From Helper: %+v\n", string(buff))
logger.Info().Msg("Bytes From Helper: " + string(buff))
var result DarajaResParams
if err := json.Unmarshal(buff, &result); err != nil {
logger.Error().Msg(err.Error())
return nil, err
}
return &result, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/handler/mpesa-express.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@ func (cl *DarajaClient) NIPush(description string, phoneNumber string, amount fl

URL := fmt.Sprintf("%s/%s", builder.BaseUrlBuilder(cl.configs.MpesaEnvironment), "mpesa/stkpush/v1/processrequest")

return handlerHelper[ExpressReqParams](payload, URL, http.MethodPost, cl.accessToken)
return handlerHelper[ExpressReqParams](cl.logger, payload, URL, http.MethodPost, cl.accessToken)
}
10 changes: 7 additions & 3 deletions pkg/handler/types.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package handler

import (
"github.com/rs/zerolog"
"github.com/silaselisha/go-daraja/pkg/internal/config"
logger "github.com/silaselisha/go-daraja/pkg/internal/log"
)

type Daraja interface {
Expand All @@ -15,6 +17,7 @@ type Daraja interface {
type DarajaClient struct {
configs *config.Configs
accessToken string
logger zerolog.Logger
}

type DarajaResParams struct {
Expand All @@ -27,9 +30,7 @@ type DarajaResParams struct {
Code string `json:"code"`
Status string `json:"status"`
}
RequestID string `json:"requestId"`
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
DarajaErrorParams
}

type DarajaErrorParams struct {
Expand All @@ -53,13 +54,16 @@ func NewDarajaClient(path string) (Daraja, error) {
return nil, err
}

logger := logger.DarajaLogger(configs)

auth, err := ClientAuth(configs)
if err != nil {
return nil, err
}

return &DarajaClient{
configs: configs,
logger: logger,
accessToken: auth.AccessToken,
}, nil
}
23 changes: 23 additions & 0 deletions pkg/internal/log/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package logger

import (
"os"

"github.com/rs/zerolog"
"github.com/silaselisha/go-daraja/pkg/internal/config"
)

func DarajaLogger(cfg *config.Configs) zerolog.Logger {
env := cfg.MpesaEnvironment

switch env {
case "sandbox":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "production":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
default:
zerolog.SetGlobalLevel(zerolog.WarnLevel)
}

return zerolog.New(os.Stdout).With().Timestamp().Logger()
}

0 comments on commit a67e518

Please sign in to comment.