Skip to content
This repository has been archived by the owner on May 23, 2024. It is now read-only.

Commit

Permalink
Add a structured way to extract traces for logging (#118)
Browse files Browse the repository at this point in the history
Since opentracing implementations differ in how they represent tracing data
(e.g., not all implementation use span and trace IDs), there isn't a generic way
to add tracing information to log messages. This PR adds a small utility to
Jaeger's zap integration that extracts structured data from a context.Context.

This is an exact clone of the code currently in UberFX's `ulog` package; for
easy re-usability, I think that this is a better place for it. I'm happy to
remove the code in UberFX once this lands.
  • Loading branch information
akshayjshah authored and yurishkuro committed Mar 19, 2017
1 parent 42d26ac commit 709b40e
Show file tree
Hide file tree
Showing 2 changed files with 136 additions and 0 deletions.
66 changes: 66 additions & 0 deletions log/zap/field.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
"context"
"fmt"

jaeger "github.com/uber/jaeger-client-go"

opentracing "github.com/opentracing/opentracing-go"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

// Trace creates a field that extracts tracing information from a context and
// includes it under the "trace" key.
//
// Because the opentracing APIs don't expose this information, the returned
// zap.Field is a no-op for contexts that don't contain a span or contain a
// non-Jaeger span.
func Trace(ctx context.Context) zapcore.Field {
if ctx == nil {
return zap.Skip()
}
return zap.Object("trace", trace{ctx})
}

type trace struct {
ctx context.Context
}

func (t trace) MarshalLogObject(enc zapcore.ObjectEncoder) error {
span := opentracing.SpanFromContext(t.ctx)
if span == nil {
return nil
}
j, ok := span.Context().(jaeger.SpanContext)
if !ok {
return nil
}
if !j.IsValid() {
return fmt.Errorf("invalid span: %v", j.SpanID())
}
enc.AddString("span", j.SpanID().String())
enc.AddString("trace", j.TraceID().String())
return nil
}
70 changes: 70 additions & 0 deletions log/zap/field_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
"context"
"testing"

jaeger "github.com/uber/jaeger-client-go"

opentracing "github.com/opentracing/opentracing-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

func TestTraceField(t *testing.T) {
assert.Equal(t, zap.Skip(), Trace(nil), "Expected Trace of a nil context to be a no-op.")

withTracedContext(func(ctx context.Context) {
enc := zapcore.NewMapObjectEncoder()
Trace(ctx).AddTo(enc)

logged, ok := enc.Fields["trace"].(map[string]interface{})
require.True(t, ok, "Expected trace to be a map.")

// We could extract the span from the context and assert specific IDs,
// but that just copies the production code. Instead, just assert that
// the keys we expect are present.
keys := make(map[string]struct{}, len(logged))
for k := range logged {
keys[k] = struct{}{}
}
assert.Equal(
t,
map[string]struct{}{"span": {}, "trace": {}},
keys,
"Expected to log span and trace IDs.",
)
})
}

func withTracedContext(f func(ctx context.Context)) {
tracer, closer := jaeger.NewTracer(
"serviceName", jaeger.NewConstSampler(true), jaeger.NewNullReporter(),
)
defer closer.Close()

ctx := opentracing.ContextWithSpan(context.Background(), tracer.StartSpan("test"))
f(ctx)
}

0 comments on commit 709b40e

Please sign in to comment.