otelzap

package module
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2024 License: BSD-2-Clause Imports: 15 Imported by: 163

README

PkgGoDev

Zap OpenTelemetry instrumentation

Zap OpenTelemetry instrumentation records Zap log messages as events on the existing span that must be passed in a context.Context as a first argument. It does not record anything if the context does not contain a span.

Installation

go get github.com/uptrace/opentelemetry-go-extra/otelzap

Usage

You need to create an otelzap.Logger using this package and pass a context to propagate the active span.

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

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

// And then pass ctx to propagate the span.
log.Ctx(ctx).Error("hello from zap",
	zap.Error(errors.New("hello world")),
	zap.String("foo", "bar"))

// Alternatively.
log.ErrorContext(ctx, "hello from zap",
	zap.Error(errors.New("hello world")),
	zap.String("foo", "bar"))

Both variants are fast and don't allocate. See example for details.

Global logger

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

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:

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,
)
sugar.InfowContext(ctx, "failed to fetch URL",
	// 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)
sugar.InfofContext(ctx, "Failed to fetch URL: %s", url)

Options

otelzap.New accepts a couple of options:

  • otelzap.WithMinLevel(zap.WarnLevel) sets the minimal zap logging level on which the log message is recorded on the span.
  • otelzap.WithErrorStatusLevel(zap.ErrorLevel) sets the minimal zap logging level on which the span status is set to codes.Error.
  • otelzap.WithCaller(true) configures the logger to annotate each event with the filename, line number, and function name of the caller. Enabled by default.
  • otelzap.WithCallerDepth(0) sets the depth of the caller stack to skip when annotating each event. Useful if you're wrapping this library with your own functions.
  • otelzap.WithStackTrace(true) configures the logger to capture logs with a stack trace. Disabled by default.
  • otelzap.WithExtraFields(true) configures the logger to add the given fields to structured log messages and to span log events.
  • otelzap.WithTraceIDField(true) configures the logger to add trace_id field to structured log messages. This option is only useful with backends that don't support OTLP and instead parse log messages to extract structured information.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReplaceGlobals added in v0.1.1

func ReplaceGlobals(logger *Logger) func()

ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a function to restore the original values. It's safe for concurrent use.

func Version

func Version() string

Version is the current release version.

Types

type Logger

type Logger struct {
	*zap.Logger
	// contains filtered or unexported fields
}

Logger is a thin wrapper for zap.Logger that adds Ctx method.

func L added in v0.1.1

func L() *Logger

L returns the global Logger, which can be reconfigured with ReplaceGlobals. It's safe for concurrent use.

func New

func New(logger *zap.Logger, opts ...Option) *Logger

func (*Logger) Clone

func (l *Logger) Clone(opts ...Option) *Logger

Clone clones the current logger applying the supplied options.

func (*Logger) Ctx

func (l *Logger) Ctx(ctx context.Context) LoggerWithCtx

Ctx returns a new logger with the context.

func (*Logger) DPanicContext

func (l *Logger) DPanicContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) DebugContext

func (l *Logger) DebugContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) ErrorContext

func (l *Logger) ErrorContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) FatalContext

func (l *Logger) FatalContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) InfoContext

func (l *Logger) InfoContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) PanicContext

func (l *Logger) PanicContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) Sugar

func (l *Logger) Sugar() *SugaredLogger

Sugar wraps the Logger to provide a more ergonomic, but slightly slower, API. Sugaring a Logger is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (*Logger) WarnContext

func (l *Logger) WarnContext(ctx context.Context, msg string, fields ...zapcore.Field)

func (*Logger) WithOptions

func (l *Logger) WithOptions(opts ...zap.Option) *Logger

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

type LoggerWithCtx

type LoggerWithCtx struct {
	// contains filtered or unexported fields
}

LoggerWithCtx is a wrapper for Logger that also carries a context.Context.

func Ctx added in v0.1.7

func Ctx(ctx context.Context) LoggerWithCtx

Ctx is a shortcut for L().Ctx(ctx).

func (LoggerWithCtx) Clone

func (l LoggerWithCtx) Clone(opts ...Option) LoggerWithCtx

Clone clones the current logger applying the supplied options.

func (LoggerWithCtx) Context

func (l LoggerWithCtx) Context() context.Context

Context returns logger's context.

func (LoggerWithCtx) DPanic

func (l LoggerWithCtx) DPanic(msg string, fields ...zapcore.Field)

DPanic logs a message at DPanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

If the logger is in development mode, it then panics (DPanic means "development panic"). This is useful for catching errors that are recoverable, but shouldn't ever happen.

func (LoggerWithCtx) Debug

func (l LoggerWithCtx) Debug(msg string, fields ...zapcore.Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (LoggerWithCtx) Error

func (l LoggerWithCtx) Error(msg string, fields ...zapcore.Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (LoggerWithCtx) Fatal

func (l LoggerWithCtx) Fatal(msg string, fields ...zapcore.Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (LoggerWithCtx) Info

func (l LoggerWithCtx) Info(msg string, fields ...zapcore.Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (LoggerWithCtx) Logger

func (l LoggerWithCtx) Logger() *Logger

Logger returns the underlying logger.

func (LoggerWithCtx) Panic

func (l LoggerWithCtx) Panic(msg string, fields ...zapcore.Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func (LoggerWithCtx) Sugar added in v0.1.8

Sugar returns a sugared logger with the context.

func (LoggerWithCtx) Warn

func (l LoggerWithCtx) Warn(msg string, fields ...zapcore.Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (LoggerWithCtx) WithOptions

func (l LoggerWithCtx) WithOptions(opts ...zap.Option) LoggerWithCtx

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

func (LoggerWithCtx) ZapLogger

func (l LoggerWithCtx) ZapLogger() *zap.Logger

ZapLogger returns the underlying zap logger.

type Option

type Option func(l *Logger)

Option applies a configuration to the given config.

func WithCaller

func WithCaller(on bool) Option

func WithCallerDepth added in v0.1.16

func WithCallerDepth(depth int) Option

WithCallerDepth allows you to you to adjust the depth of the caller by setting a number greater than 0. It can be useful if you're wrapping this library with your own helper functions.

func WithErrorStatusLevel

func WithErrorStatusLevel(lvl zapcore.Level) Option

WithErrorStatusLevel sets the minimal zap logging level on which the span status is set to codes.Error.

The default is >= zap.ErrorLevel.

func WithExtraFields added in v0.1.16

func WithExtraFields(fields ...zapcore.Field) Option

WithExtraFields configures the logger to add the given extra fields to structured log messages and the span

func WithLoggerProvider added in v0.3.0

func WithLoggerProvider(provider log.LoggerProvider) Option

WithLoggerProvider returns an Option that configures log.LoggerProvider used by a [Core] to create its log.Logger.

By default if this Option is not provided, the Handler will use the global LoggerProvider.

func WithMinLevel

func WithMinLevel(lvl zapcore.Level) Option

WithMinLevel sets the minimal zap logging level on which the log message is recorded on the span.

The default is >= zap.WarnLevel.

func WithSchemaURL added in v0.3.0

func WithSchemaURL(schemaURL string) Option

WithSchemaURL returns an Option that configures the semantic convention schema URL of the log.Logger used by a [Core]. The schemaURL should be the schema URL for the semantic conventions used in log records.

func WithStackTrace

func WithStackTrace(on bool) Option

WithStackTrace configures the logger to capture logs with a stack trace.

func WithVersion added in v0.3.0

func WithVersion(version string) Option

WithVersion returns an Option that configures the version of the log.Logger used by a [Core]. The version should be the version of the package that is being logged.

type SugaredLogger

type SugaredLogger struct {
	*zap.SugaredLogger
	// contains filtered or unexported fields
}

A SugaredLogger wraps the base Logger functionality in a slower, but less verbose, API. Any Logger can be converted to a SugaredLogger with its Sugar method.

Unlike the Logger, the SugaredLogger doesn't insist on structured logging. For each log level, it exposes three methods: one for loosely-typed structured logging, one for println-style formatting, and one for printf-style formatting. For example, SugaredLoggers can produce InfoLevel output with Infow ("info with" structured context), Info, or Infof.

func S added in v0.1.1

func S() *SugaredLogger

S returns the global SugaredLogger, which can be reconfigured with ReplaceGlobals. It's safe for concurrent use.

func (*SugaredLogger) Ctx

Ctx returns a new sugared logger with the context.

func (*SugaredLogger) DPanicfContext

func (s *SugaredLogger) DPanicfContext(ctx context.Context, template string, args ...interface{})

DPanicf uses fmt.Sprintf to log a templated message. In development, the logger then panics. (See DPanicLevel for details.)

func (*SugaredLogger) DPanicwContext

func (s *SugaredLogger) DPanicwContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

DPanicw logs a message with some additional context. In development, the logger then panics. (See DPanicLevel for details.) The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) DebugfContext

func (s *SugaredLogger) DebugfContext(ctx context.Context, template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) DebugwContext added in v0.1.15

func (s *SugaredLogger) DebugwContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) Desugar

func (s *SugaredLogger) Desugar() *Logger

Desugar unwraps a SugaredLogger, exposing the original Logger. Desugaring is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (*SugaredLogger) ErrorfContext

func (s *SugaredLogger) ErrorfContext(ctx context.Context, template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) ErrorwContext

func (s *SugaredLogger) ErrorwContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) FatalfContext

func (s *SugaredLogger) FatalfContext(ctx context.Context, template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.

func (*SugaredLogger) FatalwContext

func (s *SugaredLogger) FatalwContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) InfofContext

func (s *SugaredLogger) InfofContext(ctx context.Context, template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) InfowContext

func (s *SugaredLogger) InfowContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) PanicfContext

func (s *SugaredLogger) PanicfContext(ctx context.Context, template string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message, then panics.

func (*SugaredLogger) PanicwContext

func (s *SugaredLogger) PanicwContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) WarnfContext

func (s *SugaredLogger) WarnfContext(ctx context.Context, template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) WarnwContext

func (s *SugaredLogger) WarnwContext(
	ctx context.Context, msg string, keysAndValues ...interface{},
)

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) With

func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger

With adds a variadic number of fields to the logging context. It accepts a mix of strongly-typed Field objects and loosely-typed key-value pairs. When processing pairs, the first element of the pair is used as the field key and the second as the field value.

For example,

 sugaredLogger.With(
   "hello", "world",
   "failure", errors.New("oh no"),
   Stack(),
   "count", 42,
   "user", User{Name: "alice"},
)

is the equivalent of

unsugared.With(
  String("hello", "world"),
  String("failure", "oh no"),
  Stack(),
  Int("count", 42),
  Object("user", User{Name: "alice"}),
)

Note that the keys in key-value pairs should be strings. In development, passing a non-string key panics. In production, the logger is more forgiving: a separate error is logged, but the key-value pair is skipped and execution continues. Passing an orphaned key triggers similar behavior: panics in development and errors in production.

type SugaredLoggerWithCtx

type SugaredLoggerWithCtx struct {
	// contains filtered or unexported fields
}

func (SugaredLoggerWithCtx) DPanicf

func (s SugaredLoggerWithCtx) DPanicf(template string, args ...interface{})

DPanicf uses fmt.Sprintf to log a templated message. In development, the logger then panics. (See DPanicLevel for details.)

func (SugaredLoggerWithCtx) DPanicw

func (s SugaredLoggerWithCtx) DPanicw(msg string, keysAndValues ...interface{})

DPanicw logs a message with some additional context. In development, the logger then panics. (See DPanicLevel for details.) The variadic key-value pairs are treated as they are in With.

func (SugaredLoggerWithCtx) Debugf

func (s SugaredLoggerWithCtx) Debugf(template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func (SugaredLoggerWithCtx) Debugw

func (s SugaredLoggerWithCtx) Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

s.With(keysAndValues).Debug(msg)

func (SugaredLoggerWithCtx) Desugar

func (s SugaredLoggerWithCtx) Desugar() LoggerWithCtx

Desugar unwraps a SugaredLogger, exposing the original Logger. Desugaring is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (SugaredLoggerWithCtx) Errorf

func (s SugaredLoggerWithCtx) Errorf(template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func (SugaredLoggerWithCtx) Errorw

func (s SugaredLoggerWithCtx) Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (SugaredLoggerWithCtx) Fatalf

func (s SugaredLoggerWithCtx) Fatalf(template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.

func (SugaredLoggerWithCtx) Fatalw

func (s SugaredLoggerWithCtx) Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.

func (SugaredLoggerWithCtx) Infof

func (s SugaredLoggerWithCtx) Infof(template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func (SugaredLoggerWithCtx) Infow

func (s SugaredLoggerWithCtx) Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (SugaredLoggerWithCtx) Panicf

func (s SugaredLoggerWithCtx) Panicf(template string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message, then panics.

func (SugaredLoggerWithCtx) Panicw

func (s SugaredLoggerWithCtx) Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.

func (SugaredLoggerWithCtx) Warnf

func (s SugaredLoggerWithCtx) Warnf(template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func (SugaredLoggerWithCtx) Warnw

func (s SugaredLoggerWithCtx) Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

Directories

Path Synopsis
example module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL