otelzlog

package module
v1.0.29 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2025 License: MIT Imports: 18 Imported by: 0

README

OTEL Wrapper for zerolog

godoc license Build Status Go Coverage

The otelzlog package provides a hook to use in order to send zerolog events to OTEL logs. It performs the following actions as a part of the hook:

  1. Extracts the events from the zerolog logger.
  2. Converts the attributes into OTEL log and OTEL span attributes while attaching any error as an exception in the span.
  3. Creates a span event for the incoming log event and attaches all the associated attributes.
  4. Sets the span as failed if the log level is ERROR or greater.
  5. Sends an OTEL log event with the associated log level and all the attached log attributes.

Usage

// Initialise your OTEL configuration and save your logger to the global otel config with "go.opentelemetry.io/otel/log/global"
...
global.SetLoggerProvider(provider)
...

// Initialise the logger with as few, or as many writers as you'd like and save it to the context.
buf := new(bytes.Buffer)

ctx = otelzlog.New(ctx,
	zerolog.ConsoleWriter{Out: os.Stdout},
	zerolog.ConsoleWriter{Out: buf}
	zerolog.TestWriter{T: t},
)

// Set up your spans and traces as needed
tracer := otel.Tracer(")
ctx, span = tracer.Start(ctx, "test.segment")
time.sleep(time.Second) // do some work
defer span.End()

// Call the logger using log.Ctx(ctx) an pass in the context to the event
log.Ctx(ctx).Info().Ctx(ctx).Str("key", "value").Msg("Hello World")

// Spans will be extracted from the context and logs will be sent to your otel collector
// Attributes will be added from the logger, but not from the span

The syntax can be cumbersome, so wrapper functions are a good idea, e.g.:

package log

import (
	"context"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func Debug(ctx context.Context) *zerolog.Event {
	return log.Ctx(ctx).Debug().Ctx(ctx)
}

func Warn(ctx context.Context) *zerolog.Event {
	return log.Ctx(ctx).Warn().Ctx(ctx)
}

...

Documentation

Overview

Package otelzlog converters hold the functions that are needed to convert between zerolog and otel logging event types

Package otelzlog hook holds the hook that is attached to the zerolog logger

Package otelzlog provides a bridge between zerolog and otel logging

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(name string, options ...Option) *zerolog.Logger

New creates a new *zerolog.Logger.

Example
// Make sure there's something that can receive your otel telemetry
// and set up your OTEL exporters
recorder := otelrecorder.NewRecorder()
defer recorder.Cleanup()

// Create your new logger
logger := New(
	"test",
	WithLoggerProvider(recorder.LogProvider),
)

// Start a span and send a log event.
tracer := otel.Tracer("test.service")

func() {
	ctx, span := tracer.Start(context.Background(), "segment")
	defer span.End()
	// The context with the span is passed to the logger with the `Ctx` method.
	logger.Info().Ctx(ctx).Msg("test message")
}()

// Check that the log event has made it to the telemetry
{
	logs := recorder.GetLogs()

	if len(logs) == 1 {
		fmt.Println(logs[0].Body.AsString())
	}
}
Output:
test message

Types

type Hook

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

Hook is the parent struct of the otelzlog handler

func (*Hook) Run

func (h *Hook) Run(e *zerolog.Event, level zerolog.Level, msg string)

Run extracts the attributes and log level from the `*zerolog.Event`, and pulls the span from the passed in context in order to build the respective otel log.Record

type Option added in v1.0.23

type Option interface {
	// contains filtered or unexported methods
}

Option configures the zerolog hook.

func WithAttachSpanEvent added in v1.0.23

func WithAttachSpanEvent(attach bool) Option

WithAttachSpanEvent returns an Option that configures the Hook to attach an event to the otel span the zerolog event.

func WithAttributes added in v1.0.23

func WithAttributes(attributes ...attribute.KeyValue) Option

WithAttributes returns an Option that configures the instrumentation scope attributes of the log.Logger used by a Hook.

func WithLoggerProvider added in v1.0.23

func WithLoggerProvider(provider otelLog.LoggerProvider) Option

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

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

func WithSchemaURL added in v1.0.23

func WithSchemaURL(schemaURL string) Option

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

func WithSetSpanErrorStatus added in v1.0.24

func WithSetSpanErrorStatus(set bool, level zerolog.Level) Option

WithSetSpanErrorStatus returns an Option that configures the Hook to set the span as errored when the provided level or higher is called.

func WithSource added in v1.0.23

func WithSource(source bool, offset int) Option

WithSource returns an Option that configures the Hook to include the source location of the log record in log attributes. Offset should be increased if using a helper function to wrap the logger call.

func WithStackHandling added in v1.0.23

func WithStackHandling() Option

WithStackHandling returns an Option that sets zerolog.ErrorStackMarshaler in order to extract the stack when .Stack() is called on a .Error() event.

A Str(). called "stack" can also be passed in and will be set in the OTEL logs/traces accordingly.

func WithVersion added in v1.0.23

func WithVersion(version string) Option

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

func WithWriter added in v1.0.23

func WithWriter(w io.Writer) Option

WithWriter returns an Option that configures writers used by a Hook. Multiple writers can be specified.

Directories

Path Synopsis
Package otelrecorder provides a utility for recording OpenTelemetry logs and traces in tests.
Package otelrecorder provides a utility for recording OpenTelemetry logs and traces in tests.

Jump to

Keyboard shortcuts

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