Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support trace information in logs #26

Merged
merged 2 commits into from
Nov 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ to use the log details in the Stackdriver monitoring interface.
* [`Label`](#label)
* [`SourceLocation`](#sourcelocation)
* [`Operation`](#operation)
* [`TraceContext`](#tracecontext)

#### HTTP

Expand Down Expand Up @@ -206,6 +207,21 @@ OperationCont(id, producer string) zap.Field
OperationEnd(id, producer string) zap.Field
```

#### TraceContext

You can add trace context information to your log lines to be picked up by
Stackdriver.

```golang
TraceContext(trace string, spanId string, sampled bool, projectName string) []zap.Field
```

Like so:

```golang
logger.Error("Something happened!", zapdriver.TraceContext("105445aa7843bc8bf206b120001000", "0", true, "my-project-name")...)
```

### Pre-configured Stackdriver-optimized encoder

The Stackdriver encoder maps all Zap log levels to the appropriate
Expand Down
24 changes: 24 additions & 0 deletions trace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package zapdriver

import (
"fmt"
"go.uber.org/zap"
"strconv"
)

const (
traceKey = "logging.googleapis.com/trace"
spanKey = "logging.googleapis.com/spanId"
traceSampledKey = "logging.googleapis.com/trace_sampled"
)

// TraceContext adds the correct Stackdriver "trace", "span", "trace_sampled fields
//
// see: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
func TraceContext(trace string, spanId string, sampled bool, projectName string) []zap.Field {
return []zap.Field{
zap.String(traceKey, fmt.Sprintf("projects/%s/traces/%s", projectName, trace)),
zap.String(spanKey, spanId),
zap.String(traceSampledKey, strconv.FormatBool(sampled)),
}
}
18 changes: 18 additions & 0 deletions trace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package zapdriver

import (
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
"testing"
)

func TestTraceContext(t *testing.T) {
t.Parallel()

fields := TraceContext("105445aa7843bc8bf206b120001000", "0", true, "my-project-name")
assert.Equal(t, fields, []zap.Field{
zap.String(traceKey, "projects/my-project-name/traces/105445aa7843bc8bf206b120001000"),
zap.String(spanKey, "0"),
zap.String(traceSampledKey, "true"),
})
}