@@ -4,6 +4,7 @@ package pester
4
4
5
5
import (
6
6
"bytes"
7
+ "context"
7
8
"errors"
8
9
"fmt"
9
10
"io"
@@ -36,11 +37,12 @@ type Client struct {
36
37
Timeout time.Duration
37
38
38
39
// pester specific
39
- Concurrency int
40
- MaxRetries int
41
- Backoff BackoffStrategy
42
- KeepLog bool
43
- LogHook LogHook
40
+ Concurrency int
41
+ MaxRetries int
42
+ Backoff BackoffStrategy
43
+ KeepLog bool
44
+ LogHook LogHook
45
+ ContextLogHook ContextLogHook
44
46
45
47
SuccessReqNum int
46
48
SuccessRetryNum int
@@ -115,6 +117,9 @@ func NewExtendedClient(hc *http.Client) *Client {
115
117
// however, if KeepLog is set to true.
116
118
type LogHook func (e ErrEntry )
117
119
120
+ // ContextLogHook does the same as LogHook but with passed Context
121
+ type ContextLogHook func (ctx context.Context , e ErrEntry )
122
+
118
123
// BackoffStrategy is used to determine how long a retry request should wait until attempted
119
124
type BackoffStrategy func (retry int ) time.Duration
120
125
@@ -286,16 +291,23 @@ func (c *Client) pester(p params) (*http.Response, error) {
286
291
return
287
292
}
288
293
289
- c .log (ErrEntry {
290
- Time : time .Now (),
291
- Method : p .method ,
292
- Verb : p .verb ,
293
- URL : p .url ,
294
- Request : n ,
295
- Retry : i + 1 , // would remove, but would break backward compatibility
296
- Attempt : i ,
297
- Err : err ,
298
- })
294
+ loggingContext := context .Background ()
295
+ if p .req != nil {
296
+ loggingContext = p .req .Context ()
297
+ }
298
+
299
+ c .log (
300
+ loggingContext ,
301
+ ErrEntry {
302
+ Time : time .Now (),
303
+ Method : p .method ,
304
+ Verb : p .verb ,
305
+ URL : p .url ,
306
+ Request : n ,
307
+ Retry : i + 1 , // would remove, but would break backward compatibility
308
+ Attempt : i ,
309
+ Err : err ,
310
+ })
299
311
300
312
// if it is the last iteration, grab the result (which is an error at this point)
301
313
if i == AttemptLimit {
@@ -387,11 +399,15 @@ func (c *Client) EmbedHTTPClient(hc *http.Client) {
387
399
c .hc = hc
388
400
}
389
401
390
- func (c * Client ) log (e ErrEntry ) {
402
+ func (c * Client ) log (ctx context. Context , e ErrEntry ) {
391
403
if c .KeepLog {
392
404
c .Lock ()
393
405
defer c .Unlock ()
394
406
c .ErrLog = append (c .ErrLog , e )
407
+ } else if c .ContextLogHook != nil {
408
+ // NOTE: There is a possibility that Log Printing hook slows it down.
409
+ // but the consumer can always do the Job in a go-routine.
410
+ c .ContextLogHook (ctx , e )
395
411
} else if c .LogHook != nil {
396
412
// NOTE: There is a possibility that Log Printing hook slows it down.
397
413
// but the consumer can always do the Job in a go-routine.
0 commit comments