Skip to content

Commit

Permalink
change log output to slog
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickcping committed Nov 28, 2024
1 parent 759da76 commit 2a4a37b
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 21 deletions.
28 changes: 14 additions & 14 deletions davinci/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/http/cookiejar"
"net/url"
Expand Down Expand Up @@ -196,7 +196,7 @@ func (c *APIClient) doRequestVerbose(req *http.Request, authToken *string, args

func (c *APIClient) doRequest(reqIn DvHttpRequest, args *Params) ([]byte, *http.Response, error) {

log.Printf("Company ID in request: %s", c.companyID)
slog.Debug("Start doRequest", "Company ID", c.companyID)

req, err := http.NewRequest(reqIn.Method, reqIn.Url, strings.NewReader(reqIn.Body))
if err != nil {
Expand Down Expand Up @@ -242,10 +242,10 @@ func (c *APIClient) doRequest(reqIn DvHttpRequest, args *Params) ([]byte, *http.
}

if string(b) != "{}" {
log.Printf("Error response handled: %s", string(b))
slog.Error("Error response handled", "response", string(b))
return nil, res, errObject
} else {
log.Printf("Error response unhandled: %d", res.StatusCode)
slog.Debug("Error response unhandled", "status code", res.StatusCode)
}
}

Expand All @@ -259,7 +259,7 @@ func (c *APIClient) doRequestRetryable(companyId *string, req DvHttpRequest, arg
defer requestMutex.Unlock()

body, res, err := c.exponentialBackOffRetry(func() (any, *http.Response, error) {
log.Printf("Company ID in retryable request: %s", c.companyID)
slog.Debug("Start exponentialBackOffRetry", "Company ID", c.companyID)

// handle environment switching
if companyId != nil && *companyId != c.companyID {
Expand Down Expand Up @@ -302,14 +302,14 @@ func (c *APIClient) exponentialBackOffRetry(f SDKInterfaceFunc, isAuthCall bool)
backOffTime, isRetryable, reauthNeeded = testForRetryable(resp, err, backOffTime)

if isRetryable {
log.Printf("Attempt %d failed: %v, backing off by %s, reauth needed %t, reauth possible %t.", i+1, err, backOffTime.String(), reauthNeeded, !isAuthCall)
slog.Warn("Retryable request failed", "retry index", i+1, "error", err, "back off time", backOffTime.String(), "reauth needed", reauthNeeded, "reauth possible", !isAuthCall)
time.Sleep(backOffTime)

if reauthNeeded && !isAuthCall {
log.Printf("Attempting re-auth")
slog.Debug("Attempting re-auth")
err := c.DoSignIn(&c.companyID)
if err != nil {
log.Printf("Retry sign in failed...%s..", err)
slog.Error("Retry sign in failed", "error", err)
return obj, resp, err
}
}
Expand All @@ -320,7 +320,7 @@ func (c *APIClient) exponentialBackOffRetry(f SDKInterfaceFunc, isAuthCall bool)
return obj, resp, err
}

log.Printf("Request failed after %d attempts: %s", maxRetries, err)
slog.Warn("Retryable request failed", "Max retries", maxRetries, "error", err)

return obj, resp, err // output the final error
}
Expand All @@ -333,7 +333,7 @@ func testForRetryable(r *http.Response, err error, currentBackoff time.Duration)
if r.StatusCode == http.StatusNotImplemented || r.StatusCode == http.StatusServiceUnavailable || r.StatusCode == http.StatusTooManyRequests {
retryAfter, err := parseRetryAfterHeader(r)
if err != nil {
log.Printf("Cannot parse the expected \"Retry-After\" header: %s", err)
slog.Warn("Cannot parse the expected \"Retry-After\" header", "error", err)
backoffDuration = currentBackoff * 2
}

Expand All @@ -355,7 +355,7 @@ func testForRetryable(r *http.Response, err error, currentBackoff time.Duration)
}

if slices.Contains(retryAbleCodes, r.StatusCode) {
log.Printf("HTTP status code %d detected, available for retry", r.StatusCode)
slog.Debug("Retryable HTTP status code found", "http status code", r.StatusCode)
return backoffDuration, true, false
}
}
Expand All @@ -366,20 +366,20 @@ func testForRetryable(r *http.Response, err error, currentBackoff time.Duration)

case ErrorResponse:
if t.HttpResponseCode == http.StatusUnauthorized && t.Code == DV_ERROR_CODE_INVALID_TOKEN_FOR_ENVIRONMENT {
log.Printf("Client unauthorized for the environment, available for retry (re-auth needed): %v", err)
slog.Warn("Client unauthorized for the environment, available for retry (re-auth needed)", "error", err)
backoffDuration += (2 * time.Second)
return backoffDuration, true, true
}

default:
if res1, matchErr := regexp.MatchString(`^http: ContentLength=[0-9]+ with Body length [0-9]+$`, err.Error()); matchErr == nil && res1 {
log.Printf("HTTP content error detected, available for retry (re-auth needed): %v", err)
slog.Warn("HTTP content error detected, available for retry (re-auth needed)", "error", err)
backoffDuration += (2 * time.Second)
return backoffDuration, true, true
}

if res1, matchErr := regexp.MatchString(`error\=AuthenticationFailed\&error_description\=unknownError2`, err.Error()); matchErr == nil && res1 {
log.Printf("Authentication unknown2 error detected, available for retry: %v", err)
slog.Warn("Authentication unknown2 error detected, available for retry", "error", err)
backoffDuration += (2 * time.Second)
return backoffDuration, true, false
}
Expand Down
4 changes: 2 additions & 2 deletions davinci/connections.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package davinci
import (
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
)

Expand Down Expand Up @@ -99,7 +99,7 @@ func (c *APIClient) CreateConnectionWithResponse(companyId string, payload *Conn
}

if *connResponse.CompanyID != companyId {
log.Printf("%s != %s", *connResponse.CompanyID, companyId)
slog.Error("Connection created with wrong companyId", "Company ID (Response)", *connResponse.CompanyID, "Company ID (Intended)", companyId)
return nil, res, fmt.Errorf("Connection created with wrong companyId")
}

Expand Down
4 changes: 2 additions & 2 deletions davinci/flows.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package davinci
import (
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
)

Expand All @@ -15,7 +15,7 @@ func (c *APIClient) ReadFlows(companyId string, args *Params) ([]Flow, error) {

func (c *APIClient) ReadFlowsWithResponse(companyId string, args *Params) ([]Flow, *http.Response, error) {
if args != nil && args.Page != "" {
log.Println("Param.Page found, not allowed, removing.")
slog.Warn("Param.Page found, not allowed, removing.")
args.Page = ""
}

Expand Down
5 changes: 2 additions & 3 deletions internal/test/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"os"

Expand All @@ -29,7 +28,7 @@ func newTestClient() (*dv.APIClient, error) {
byteValue, _ := io.ReadAll(jsonFile)
errJ := json.Unmarshal(byteValue, &envs)
if errJ != nil {
log.Fatalf("failed to unmarshal json %v: ", errJ)
return nil, fmt.Errorf("failed to unmarshal json %v: ", errJ)
}
username = envs.PINGONE_USERNAME
password = envs.PINGONE_PASSWORD
Expand All @@ -50,7 +49,7 @@ func newTestClient() (*dv.APIClient, error) {
}
client, err := dv.NewClient(&cInput)
if err != nil {
log.Fatalf("failed to make client %v: ", err)
return nil, fmt.Errorf("failed to make client %v: ", err)
}
return client, nil
}
Expand Down

0 comments on commit 2a4a37b

Please sign in to comment.