Skip to content

Commit a0c4cd9

Browse files
Merge pull request #55 from snabble/use-tracex
Use tracex for all otel needs
2 parents 2f5bce8 + 0c9c253 commit a0c4cd9

18 files changed

+422
-34
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
language: go
22
go:
3-
- 1.18.x
3+
- 1.19.x
44
before_install:
55
- go install honnef.co/go/tools/cmd/staticcheck@latest
66
script:

go.mod

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
11
module github.com/snabble/go-logging/v2
22

3-
go 1.18
3+
go 1.19
44

55
require (
66
github.com/sirupsen/logrus v1.9.0
77
github.com/stretchr/testify v1.8.1
8-
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.18
8+
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.20
99
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.38.0
1010
go.opentelemetry.io/otel v1.12.0
11-
go.opentelemetry.io/otel/sdk v1.11.1
11+
go.opentelemetry.io/otel/sdk v1.11.2
1212
go.opentelemetry.io/otel/trace v1.12.0
13-
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2
1413
)
1514

1615
require (
1716
github.com/davecgh/go-spew v1.1.1 // indirect
1817
github.com/felixge/httpsnoop v1.0.3 // indirect
1918
github.com/go-logr/logr v1.2.3 // indirect
2019
github.com/go-logr/stdr v1.2.2 // indirect
20+
github.com/kr/text v0.2.0 // indirect
2121
github.com/pmezard/go-difflib v1.0.0 // indirect
22-
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.18 // indirect
22+
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.20 // indirect
2323
go.opentelemetry.io/otel/metric v0.35.0 // indirect
2424
golang.org/x/sys v0.4.0 // indirect
25+
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
2526
gopkg.in/yaml.v3 v3.0.1 // indirect
2627
)

go.sum

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
12
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
23
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
34
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -9,6 +10,12 @@ github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbV
910
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
1011
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
1112
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
13+
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
14+
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
15+
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
16+
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
17+
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
18+
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
1219
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
1320
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
1421
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
@@ -21,27 +28,26 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
2128
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
2229
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
2330
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
24-
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.18 h1:3UVwJbeF2xV7r7rB1KLGsYlZGoF9P25VkyilyI5zqmY=
25-
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.18/go.mod h1:1jmEHPb6FL22RcHSsVaPg9UH1IFOV0hGFdZYgkyJeag=
26-
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.18 h1:zsEhOhAfpNejDoJQi0gLsnN1bf3x2h7dTF7XNS2MJPE=
27-
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.18/go.mod h1:7le+eIjcOjMMZ7QJqmzZFxcmZNvIK1qBdsYkHzaYuMU=
31+
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.20 h1:g8zAGsjsiJzbtFc8S7n0do48LIK7k7MtBNmTKftDXzM=
32+
github.com/uptrace/opentelemetry-go-extra/otellogrus v0.1.20/go.mod h1:S3D8uTHdX/koXbokZkn+mkKbMLHhUGKxKzhGK6lDVnY=
33+
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.20 h1:+4xV/g5ncPPNcHUBbj9JKEuee7EggpDlAnJIHnBymOo=
34+
github.com/uptrace/opentelemetry-go-extra/otelutil v0.1.20/go.mod h1:V0FSB+VaY2zak6iCOf2jmyA5YOj6LSB/X+AdkBUENVg=
2835
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.38.0 h1:rTxmym+VN9f6ajzNtITVgyvZrNbpLt3NHr3suLLHLEQ=
2936
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.38.0/go.mod h1:w6xNm+kC506KNs5cknSHal6dtdRnc4uema0uN9GSQc0=
3037
go.opentelemetry.io/otel v1.12.0 h1:IgfC7kqQrRccIKuB7Cl+SRUmsKbEwSGPr0Eu+/ht1SQ=
3138
go.opentelemetry.io/otel v1.12.0/go.mod h1:geaoz0L0r1BEOR81k7/n9W4TCXYCJ7bPO7K374jQHG0=
3239
go.opentelemetry.io/otel/metric v0.35.0 h1:aPT5jk/w7F9zW51L7WgRqNKDElBdyRLGuBtI5MX34e8=
3340
go.opentelemetry.io/otel/metric v0.35.0/go.mod h1:qAcbhaTRFU6uG8QM7dDo7XvFsWcugziq/5YI065TokQ=
34-
go.opentelemetry.io/otel/sdk v1.11.1 h1:F7KmQgoHljhUuJyA+9BiU+EkJfyX5nVVF4wyzWZpKxs=
35-
go.opentelemetry.io/otel/sdk v1.11.1/go.mod h1:/l3FE4SupHJ12TduVjUkZtlfFqDCQJlOlithYrdktys=
41+
go.opentelemetry.io/otel/sdk v1.11.2 h1:GF4JoaEx7iihdMFu30sOyRx52HDHOkl9xQ8SMqNXUiU=
42+
go.opentelemetry.io/otel/sdk v1.11.2/go.mod h1:wZ1WxImwpq+lVRo4vsmSOxdd+xwoUJ6rqyLc3SyX9aU=
3643
go.opentelemetry.io/otel/trace v1.12.0 h1:p28in++7Kd0r2d8gSt931O57fdjUyWxkVbESuILAeUc=
3744
go.opentelemetry.io/otel/trace v1.12.0/go.mod h1:pHlgBynn6s25qJ2szD+Bv+iwKJttjHSI3lUAyf0GNuQ=
3845
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
3946
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
4047
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
41-
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=
42-
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=
43-
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
4448
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
49+
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
50+
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
4551
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
4652
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
4753
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

helper.go

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"time"
1111

1212
"github.com/sirupsen/logrus"
13-
"github.com/uptrace/opentelemetry-go-extra/otellogrus"
13+
"github.com/snabble/go-logging/v2/tracex"
1414
)
1515

1616
// AccessLogCookiesBlacklist The list of cookies which should not be logged
@@ -58,13 +58,7 @@ func SetWithConfig(level string, config *LogConfig) error {
5858
}
5959

6060
if config.EnableTraces {
61-
logger.AddHook(otellogrus.NewHook(otellogrus.WithLevels(
62-
logrus.PanicLevel,
63-
logrus.FatalLevel,
64-
logrus.ErrorLevel,
65-
logrus.WarnLevel,
66-
logrus.InfoLevel,
67-
)))
61+
logger.AddHook(tracex.NewLogrusHook())
6862
}
6963

7064
logger.Level = l

log_middleware.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"strings"
99
"time"
1010

11-
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
11+
"github.com/snabble/go-logging/v2/tracex"
1212
)
1313

1414
type LogMiddleware struct {
@@ -17,7 +17,7 @@ type LogMiddleware struct {
1717

1818
func NewLogMiddleware(next http.Handler) http.Handler {
1919
if Log.config.EnableTraces {
20-
return otelhttp.NewHandler(&LogMiddleware{Next: next}, "common")
20+
return tracex.NewHandler(&LogMiddleware{Next: next}, "common")
2121
}
2222
return &LogMiddleware{Next: next}
2323
}

logger_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import (
44
"bytes"
55
"encoding/json"
66
"errors"
7+
"fmt"
78
"net/http"
89
"os"
910
"testing"
1011
"time"
1112

1213
"github.com/sirupsen/logrus"
1314
"github.com/stretchr/testify/assert"
14-
"golang.org/x/xerrors"
1515
)
1616

1717
type logRecord struct {
@@ -62,12 +62,12 @@ func Test_Logger_WithError(t *testing.T) {
6262
Log.Out = b
6363

6464
err := func() error {
65-
return xerrors.Errorf("found an error: %w", errors.New("an error occurred"))
65+
return fmt.Errorf("found an error: %w", errors.New("an error occurred"))
6666
}()
6767
Log.WithError(err).Error("oops")
6868

6969
// print(b.String())
70-
a.Regexp(`^time.* level\=error msg\=oops error\="found an error: an error occurred" stacktrace\=".*"`, b.String())
70+
a.Regexp(`^time.* level\=error msg\=oops error\="found an error: an error occurred"`, b.String())
7171
}
7272

7373
func Test_Logger_Call(t *testing.T) {

logstash_formatter.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"time"
88

99
"github.com/sirupsen/logrus"
10-
"go.opentelemetry.io/otel/trace"
10+
"github.com/snabble/go-logging/v2/tracex"
1111
)
1212

1313
// Taken from github.com/bshuster-repo/logrus-logstash-hook
@@ -78,11 +78,7 @@ func (f *LogstashFormatter) FormatWithPrefix(entry *logrus.Entry, prefix string)
7878
fields["type"] = f.Type
7979
}
8080

81-
spanContext := trace.SpanContextFromContext(entry.Context)
82-
if spanContext.IsValid() {
83-
fields["trace"] = spanContext.TraceID()
84-
fields["span"] = spanContext.SpanID()
85-
}
81+
tracex.TraceAndSpan(entry.Context, fields)
8682

8783
serialized, err := json.Marshal(fields)
8884
if err != nil {

trace_provider_test.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package logging
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"testing"
7+
8+
"github.com/sirupsen/logrus"
9+
"github.com/sirupsen/logrus/hooks/writer"
10+
"github.com/snabble/go-logging/v2/tracex"
11+
"github.com/stretchr/testify/assert"
12+
"github.com/stretchr/testify/require"
13+
"go.opentelemetry.io/otel"
14+
"go.opentelemetry.io/otel/trace"
15+
)
16+
17+
func Test_NewGlobalNoopTraceProvider_SetsTheGlobalProvider(t *testing.T) {
18+
capture := capturingLogger(t)
19+
defer func() { _ = Set("info", true) }()
20+
21+
provider := tracex.NewGlobalNoopTraceProvider("sampleApp", "v1.0.0")
22+
23+
ctx, span := startSpan()
24+
defer span.End()
25+
Log.WithContext(ctx).Info("meee")
26+
27+
require.NoError(t, provider.Shutdown(context.Background()))
28+
assert.NotContains(t, capture.String(), "00000000000000000000000000000000")
29+
assert.Contains(t, capture.String(), "trace")
30+
assert.Contains(t, capture.String(), "span")
31+
}
32+
33+
func Test_NewGlobalNoopTraceProvider_DoesNotTraceIfNotActivated(t *testing.T) {
34+
capture := capturingLogger(t)
35+
defer func() { _ = Set("info", true) }()
36+
37+
ctx, span := startSpan()
38+
defer span.End()
39+
Log.WithContext(ctx).Info("meee")
40+
41+
assert.NotContains(t, capture.String(), "trace")
42+
assert.NotContains(t, capture.String(), "span")
43+
}
44+
45+
func startSpan() (context.Context, trace.Span) {
46+
return otel.Tracer("global").Start(context.Background(), "test")
47+
}
48+
49+
func capturingLogger(t *testing.T) *bytes.Buffer {
50+
t.Helper()
51+
52+
capture := &bytes.Buffer{}
53+
err := SetWithConfig("info", &LogConfig{EnableTraces: true, EnableTextLogging: false})
54+
require.NoError(t, err)
55+
Log.Hooks.Add(&writer.Hook{Writer: capture, LogLevels: logrus.AllLevels})
56+
return capture
57+
}

tracex/datamap/propagator.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package datamap
2+
3+
import (
4+
"context"
5+
"strings"
6+
7+
"github.com/snabble/go-logging/v2/tracex/propagation"
8+
)
9+
10+
type Propagator struct {
11+
propagation propagation.TraceContext
12+
}
13+
14+
func NewPropagator() *Propagator {
15+
return &Propagator{propagation: propagation.TraceContext{}}
16+
}
17+
18+
// Container contains a datamap
19+
type Container interface {
20+
GetDataMap() map[string]string
21+
}
22+
23+
func (p *Propagator) Extract(ctx context.Context, owner Container) context.Context {
24+
return p.propagation.Extract(ctx, dataMap(owner.GetDataMap()))
25+
}
26+
27+
func (p *Propagator) Inject(ctx context.Context) map[string]string {
28+
carrier := dataMap{}
29+
p.propagation.Inject(ctx, carrier)
30+
return carrier
31+
}
32+
33+
const tracingPrefix = "__tracing__"
34+
35+
type dataMap map[string]string
36+
37+
func (dm dataMap) Get(key string) string {
38+
value, ok := dm[tracingPrefix+key]
39+
if !ok {
40+
return ""
41+
}
42+
return value
43+
}
44+
45+
func (dm dataMap) Set(key string, value string) {
46+
dm[tracingPrefix+key] = value
47+
}
48+
49+
func (dm dataMap) Keys() []string {
50+
keys := make([]string, 0, len(dm))
51+
for key := range dm {
52+
if !strings.HasPrefix(key, tracingPrefix) {
53+
continue
54+
}
55+
keys = append(keys, strings.TrimPrefix(key, tracingPrefix))
56+
}
57+
return keys
58+
}

tracex/datamap/propagator_test.go

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package datamap
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"go.opentelemetry.io/otel/trace"
9+
)
10+
11+
const (
12+
traceID = "11000000000000000000000000000000"
13+
spanID = "0100000000000000"
14+
traceAndSpan = "00-11000000000000000000000000000000-0100000000000000-00"
15+
)
16+
17+
var (
18+
spanContext = trace.NewSpanContext(
19+
trace.SpanContextConfig{
20+
TraceID: trace.TraceID{0x11},
21+
SpanID: trace.SpanID{0x01},
22+
})
23+
)
24+
25+
func Test_Inject_DataMapIsFilledWithTrace(t *testing.T) {
26+
ctx := trace.ContextWithRemoteSpanContext(context.Background(), spanContext)
27+
ctx, _ = traceProvider().
28+
Tracer("__traced_app__").Start(ctx, "test")
29+
30+
inject := propagator().Inject(ctx)
31+
32+
container := dataMap(inject)
33+
assert.Equal(t, container.Keys(), []string{"traceparent"})
34+
assert.Equal(t, traceAndSpan, container.Get("traceparent"))
35+
}
36+
37+
type someDataMapContainer struct {
38+
dm map[string]string
39+
}
40+
41+
func (s someDataMapContainer) GetDataMap() map[string]string {
42+
return s.dm
43+
}
44+
45+
func Test_Extract_PopulatesContext(t *testing.T) {
46+
workItem := someDataMapContainer{dm: map[string]string{"__tracing__traceparent": traceAndSpan}}
47+
48+
ctx := context.Background()
49+
extractedCtx := propagator().Extract(ctx, workItem)
50+
51+
span := trace.SpanContextFromContext(extractedCtx)
52+
assert.True(t, span.IsRemote())
53+
assert.Equal(t, traceID, span.TraceID().String())
54+
assert.Equal(t, spanID, span.SpanID().String())
55+
}
56+
57+
func Test_Extract_DoesNotFailOnEmptyDataMap(t *testing.T) {
58+
workItem := someDataMapContainer{dm: map[string]string{}}
59+
60+
ctx := context.Background()
61+
extractedCtx := propagator().Extract(ctx, workItem)
62+
63+
span := trace.SpanContextFromContext(extractedCtx)
64+
assert.False(t, span.IsRemote())
65+
assert.False(t, span.IsValid())
66+
}
67+
68+
func propagator() *Propagator {
69+
return NewPropagator()
70+
}
71+
72+
func traceProvider() trace.TracerProvider {
73+
return trace.NewNoopTracerProvider()
74+
}

0 commit comments

Comments
 (0)