polygon-io / client-go

The official Go client library for the Polygon REST and WebSocket API.
MIT License
127 stars 36 forks source link

Show trace on error #391

Open justinpolygon opened 7 months ago

justinpolygon commented 7 months ago

Fixes https://github.com/polygon-io/client-go/issues/390. When using models.WithTrace(true) there was an issue where tracing data was not captured for failed API requests. Now, tracing consistently logs request and response details, including status codes, for both successful and erroneous responses.

Example:

// Stocks - Aggregates (Bars)
// https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksticker__range__multiplier___timespan___from___to
// https://github.com/polygon-io/client-go/blob/master/rest/aggs.go
package main

import (
    "context"
    "log"
    "os"
    "time"

    polygon "github.com/polygon-io/client-go/rest"
    "github.com/polygon-io/client-go/rest/models"
)

func main() {

    client := polygon.New(os.Getenv("POLYGON_API_KEY"))
    adjusted := true
    limit := 50000
    from := time.Now().AddDate(-2, 0, 0)
    to := time.Now()
    params := models.ListAggsParams{
        Ticker:     "AAPL",
        From:       models.Millis(from),
        To:         models.Millis(to),
        Limit:      &limit,
        Adjusted:   &adjusted,
        Timespan:   models.Day,
        Multiplier: 1,
    }
    iter := client.ListAggs(context.TODO(), &params, models.WithTrace(true))
    count := 0
    for iter.Next() {
        count += 1
    }
    if iter.Err() != nil {
        log.Fatal(iter.Err())
    }

    log.Printf("Found %d results", count)

}

Successful:

$ go run example.go
Request URL: /v2/aggs/ticker/AAPL/range/1/day/1643037105510/1706109105510?adjusted=true&limit=50000
Request Headers: map[Accept-Encoding:[gzip] Authorization:[REDACTED] User-Agent:[Polygon.io GoClient/v1.16.0]]
Response Status Code: 200
Response Headers: map[Content-Encoding:[gzip] Content-Type:[application/json] Date:[Wed, 24 Jan 2024 15:11:45 GMT] Server:[nginx/1.19.2] Strict-Transport-Security:[max-age=15724800; includeSubDomains] Vary:[Accept-Encoding] X-Request-Id:[5f4376efbe55fd713d23cf38c7903b45]]
2024/01/24 07:11:45 Found 502 results

Failed (no trace info was shown before):

$ go run example.go
Request URL: /v2/aggs/ticker/AAPL/range/1/day/1643037106633/1706109106634?adjusted=true&limit=50000
Request Headers: map[Accept-Encoding:[gzip] Authorization:[REDACTED] User-Agent:[Polygon.io GoClient/v1.16.0]]
Response Status Code: 429
Response Headers: map[Content-Length:[206] Content-Type:[application/json] Date:[Wed, 24 Jan 2024 15:11:46 GMT] Server:[nginx/1.19.2] Strict-Transport-Security:[max-age=15724800; includeSubDomains] X-Request-Id:[378d2ba8c07a2fd0fe4bd2c77d6ab4ed]]
2024/01/24 07:11:46 Found 0 results