Skip to content

Commit b868528

Browse files
authored
Merge pull request #77 from snabble/log-trace-call
Include context in call logs
2 parents 4490517 + e266cd1 commit b868528

File tree

2 files changed

+32
-9
lines changed

2 files changed

+32
-9
lines changed

helper.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -184,32 +184,32 @@ func fieldsForCall(r *http.Request, resp *http.Response, start time.Time, err er
184184
}
185185

186186
func logCall(fields logrus.Fields, r *http.Request, resp *http.Response, err error) {
187-
ctxErr := r.Context().Err()
188-
if ctxErr != nil {
189-
Log.WithFields(fields).Info(fmt.Sprintf("Context canceled for %s-> %s with error: %s", r.Method, r.URL.String(), ctxErr.Error()))
187+
entry := Log.WithContext(r.Context()).WithFields(fields)
188+
189+
if ctxErr := r.Context().Err(); ctxErr != nil {
190+
entry.Info(fmt.Sprintf("Context canceled for %s-> %s with error: %s", r.Method, r.URL.String(), ctxErr.Error()))
190191
return
191192
}
192193

193194
if err != nil {
194-
Log.WithFields(fields).Error(err)
195+
entry.Error(err)
195196
return
196197
}
197198

198199
if resp != nil {
199-
e := Log.WithFields(fields)
200200
msg := fmt.Sprintf("%d %s-> %s", resp.StatusCode, r.Method, r.URL.String())
201201

202202
if resp.StatusCode >= 200 && resp.StatusCode <= 399 {
203-
e.Info(msg)
203+
entry.Info(msg)
204204
} else if resp.StatusCode >= 400 && resp.StatusCode <= 499 {
205-
e.Warn(msg)
205+
entry.Warn(msg)
206206
} else {
207-
e.Error(msg)
207+
entry.Error(msg)
208208
}
209209
return
210210
}
211211

212-
Log.WithFields(fields).Warn("call, but no response given")
212+
entry.Warn("call, but no response given")
213213
}
214214

215215
// Cacheinfo logs the hit information an accessing a resource

helper_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,36 @@
11
package logging
22

33
import (
4+
"context"
5+
"net/http"
46
"testing"
7+
"time"
58

9+
"github.com/snabble/go-logging/v2/tracex"
610
"github.com/stretchr/testify/assert"
11+
"github.com/stretchr/testify/require"
712
)
813

914
func Test_LifecycleStart_AcceptsNil(t *testing.T) {
1015
assert.NotPanics(t, func() {
1116
LifecycleStart("app", nil)
1217
})
1318
}
19+
20+
func Test_Call_UsesTrace(t *testing.T) {
21+
capture := capturingLogger(t)
22+
defer func() { _ = Set("info", true) }()
23+
provider := tracex.NewGlobalNoopTraceProvider("sampleApp", "v1.0.0")
24+
25+
ctx, span := startSpan()
26+
defer span.End()
27+
28+
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
29+
30+
Call(req, &http.Response{}, time.Time{}, nil)
31+
32+
require.NoError(t, provider.Shutdown(context.Background()))
33+
assert.NotContains(t, capture.String(), "00000000000000000000000000000000")
34+
assert.Contains(t, capture.String(), "trace")
35+
assert.Contains(t, capture.String(), "span")
36+
}

0 commit comments

Comments
 (0)