Skip to content

Commit

Permalink
feat: add otelzap.Ctx shortcut
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Nov 26, 2021
1 parent 853daf8 commit 2d3c044
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
44 changes: 34 additions & 10 deletions otelzap/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
)

// Wrap zap logger to extend Zap with API that accepts a context.Context.
log := otelzap.New(zap.L())
log := otelzap.New(zap.NewExample())

// And then pass ctx to propagate the span.
log.Ctx(ctx).Error("hello from zap",
Expand All @@ -40,25 +40,49 @@ log.ErrorContext(ctx, "hello from zap",

Both variants are fast and don't allocate. See [example](/example/) for details.

### Global logger

Just like Zap, otelzap provides a global logger that can be set with `otelzap.ReplaceGlobals`:

```go
package main

import (
"go.uber.org/zap"
"github.com/uptrace/opentelemetry-go-extra/otelzap"
)

func main() {
logger := otelzap.New(zap.NewExample())
defer logger.Sync()

undo := otelzap.ReplaceGlobals(logger)
defer undo()

otelzap.L().Info("replaced zap's global loggers")
otelzap.Ctx(context.TODO()).Info("... and with context")
}
```

### Sugared logger

You can also use sugared logger API in a similar way:

```go
log := otelzap.New(zap.L())
log := otelzap.New(zap.NewExample())
sugar := log.Sugar()

sugar.Ctx(ctx).Infow("failed to fetch URL",
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
)
sugar.InfowContext(ctx, "failed to fetch URL",
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
)

sugar.Ctx(ctx).Infof("Failed to fetch URL: %s", url)
Expand Down
6 changes: 6 additions & 0 deletions otelzap/global.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package otelzap

import (
"context"
"sync"

"go.uber.org/zap"
Expand Down Expand Up @@ -30,6 +31,11 @@ func S() *SugaredLogger {
return s
}

// Ctx is a shortcut for L().Ctx(ctx).
func Ctx(ctx context.Context) LoggerWithCtx {
return L().Ctx(ctx)
}

// ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a
// function to restore the original values. It's safe for concurrent use.
func ReplaceGlobals(logger *Logger) func() {
Expand Down

0 comments on commit 2d3c044

Please sign in to comment.