zapr

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2023 License: BSD-3-Clause Imports: 17 Imported by: 3

README

Zapr

License GoDev Reference Go Report Card

Zapr provides a logr.LogSink implementation using zap. It includes optional flag registration, Prometheus metrics, and a standard library *log.Logger adapter.

Example

addr := flag.String("http-address", ":8080", "HTTP server listen address.")
zaprObserver := zaprprom.NewObserver()
zaprOptions := zapr.RegisterFlags(flag.CommandLine, zapr.AllOptions(
    zapr.WithObserver(zaprObserver),
    zapr.WithLevel(2), // Override default logging level.
)...)
flag.Parse()

log, sink := zapr.NewLogger(zaprOptions...)
defer sink.Flush() // For most GOOS (linux and darwin), flushing to stderr is a no-op.
log.Info("Hello, zap logr with option flags!")

reg := prometheus.NewRegistry()
reg.MustRegister(
    collectors.NewGoCollector(),
    collectors.NewBuildInfoCollector(),
    collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
    zaprObserver, // Register Observer with Prometheus.
)
log.Info("Hello, zap logr Prometheus metrics!")

mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))

srv := http.Server{
    Addr:     *addr,
    Handler:  mux,
    ErrorLog: zapr.NewStdErrorLogger(sink), // Adapt LogSink to stdlib *log.Logger.
}
if err := srv.ListenAndServe(); err != nil {
    log.Error(err, "Failed to serve HTTP")
}

Documentation

Overview

Package zapr provides a logr.Logger interface around a zap implementation, including metrics and a standard library log.Logger adapter.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewStdErrorLogger

func NewStdErrorLogger(s logr.CallDepthLogSink) *log.Logger

NewStdErrorLogger returns a *log.Logger which writes to the supplied Logger's Error method.

func NewStdInfoLogger

func NewStdInfoLogger(s logr.CallDepthLogSink) *log.Logger

NewStdInfoLogger returns a *log.Logger which writes to the supplied Logger's Info method.

Types

type LazyLogSink added in v0.5.0

type LazyLogSink interface {
	LogSink

	// SetSink sets the underlying LogSink for the LazyLogSink and all of
	// its descendants created by WithDepth, WithName, or WithValues.
	SetSink(LogSink)
}

LazyLogSink is a LogSink whose underlying implementation can be updated after it's been used to create log.Loggers.

func NewLazyLogSink added in v0.5.0

func NewLazyLogSink() LazyLogSink

NewLazyLogSink returns a new Sink that discards logs until SetSink is called.

type LogSink added in v0.2.0

type LogSink interface {
	logr.LogSink
	logr.CallDepthLogSink

	// Underlying returns the underlying *zap.Logger with no caller skips.
	// Any names or added keys and values remain.
	Underlying() *zap.Logger

	// Flush writes any buffered data to the underlying io.Writer.
	Flush() error
}

LogSink represents the ability to log messages, both errors and not.

func NewLogSink added in v0.2.0

func NewLogSink(options ...Option) LogSink

NewLogSink returns a new LogSink with the given options.

func NewLogger

func NewLogger(options ...Option) (logr.Logger, LogSink)

NewLogger returns a new Logger with the given options and a flush function.

Example
package main

import (
	"flag"
	"net/http"

	"bursavich.dev/zapr"
	"bursavich.dev/zapr/zaprprom"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	addr := flag.String("http-address", ":8080", "HTTP server listen address.")
	zaprObserver := zaprprom.NewObserver()
	zaprOptions := zapr.RegisterFlags(flag.CommandLine, zapr.AllOptions(
		zapr.WithObserver(zaprObserver),
		zapr.WithLevel(2), // Override default logging level.
	)...)
	flag.Parse()

	log, sink := zapr.NewLogger(zaprOptions...)
	defer sink.Flush() // For most GOOS (linux and darwin), flushing to stderr is a no-op.
	log.Info("Hello, zap logr with option flags!")

	reg := prometheus.NewRegistry()
	reg.MustRegister(
		collectors.NewGoCollector(),
		collectors.NewBuildInfoCollector(),
		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
		zaprObserver, // Register Observer with Prometheus.
	)
	log.Info("Hello, zap logr Prometheus metrics!")

	mux := http.NewServeMux()
	mux.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))

	srv := http.Server{
		Addr:     *addr,
		Handler:  mux,
		ErrorLog: zapr.NewStdErrorLogger(sink), // Adapt LogSink to stdlib *log.Logger.
	}
	if err := srv.ListenAndServe(); err != nil {
		log.Error(err, "Failed to serve HTTP")
	}
}
Output:

type Observer added in v0.2.0

type Observer interface {
	// Init initializes metrics for the named logger when it's created.
	// Logger names are not required to be unique and it may be called
	// with a duplicate name at any time.
	Init(logger string)

	// ObserveEntryLogged observes logged entry metrics for the named logger, at
	// the given level, and with the given bytes.
	ObserveEntryLogged(logger string, level string, bytes int)

	// ObserveEncoderError observes an error encoding an entry for the named logger.
	ObserveEncoderError(logger string)
}

Observer represent the ability to observe log metrics.

type Option added in v0.2.0

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

An Option applies optional configuration.

func AllOptions added in v0.2.0

func AllOptions(overrides ...Option) []Option

AllOptions returns all Options with the given overrides.

func RegisterFlags added in v0.2.0

func RegisterFlags(fs *flag.FlagSet, options ...Option) []Option

RegisterFlags registers the given Options with the FlagSet.

func WithCallerEnabled added in v0.2.0

func WithCallerEnabled(enabled bool) Option

WithCallerEnabled returns an Option that sets whether the caller field is enabled. It's enabled by default.

func WithCallerEncoder added in v0.2.0

func WithCallerEncoder(encoder encoding.CallerEncoder) Option

WithCallerEncoder returns an Option that sets the caller encoder. The default encoding is short.

func WithCallerKey added in v0.2.0

func WithCallerKey(key string) Option

WithCallerKey returns an Option that sets the caller key. The default value is "caller".

func WithDevelopmentOptions added in v0.2.0

func WithDevelopmentOptions(enabled bool) Option

WithDevelopmentOptions returns an Option that enables a set of development-friendly options.

func WithDurationEncoder added in v0.2.0

func WithDurationEncoder(encoder encoding.DurationEncoder) Option

WithDurationEncoder returns an Option that sets the duration encoder. The default encoding is seconds.

func WithEncoder added in v0.2.0

func WithEncoder(encoder encoding.Encoder) Option

WithEncoder returns an Option that sets the encoder. The default value is a JSONEncoder.

func WithErrorKey added in v0.2.0

func WithErrorKey(key string) Option

WithErrorKey returns an Option that sets the error key. The default value is "error".

func WithFunctionKey added in v0.2.0

func WithFunctionKey(key string) Option

WithFunctionKey returns an Option that sets the function key. The default value is empty.

func WithLevel added in v0.2.0

func WithLevel(level int) Option

WithLevel returns an Option that sets the level. The default value is 0.

func WithLevelEncoder added in v0.2.0

func WithLevelEncoder(encoder encoding.LevelEncoder) Option

WithLevelEncoder returns an Option that sets the level encoder. The default encoding is uppercase.

func WithLevelKey added in v0.2.0

func WithLevelKey(key string) Option

WithLevelKey returns an Option that sets the level key. The default value is "level".

func WithLineEnding added in v0.2.0

func WithLineEnding(ending string) Option

WithLineEnding returns an Option that sets the line-ending. The default value is "\n".

func WithMessageKey added in v0.2.0

func WithMessageKey(key string) Option

WithMessageKey returns an Option that sets the message key. The default value is "message".

func WithName added in v0.2.0

func WithName(name string) Option

WithName returns an Option that sets the name. The default value is empty.

func WithNameKey added in v0.2.0

func WithNameKey(key string) Option

WithNameKey returns an Option that sets the name key. The default value is "logger".

func WithObserver added in v0.3.0

func WithObserver(observer Observer) Option

WithObserver returns an Option that sets the metrics Observer. There is no default Observer.

func WithSampler added in v0.2.0

func WithSampler(tick time.Duration, first, thereafter int, opts ...zapcore.SamplerOption) Option

WithSampler returns an Option that sets sampler options. The default is 1s tick, 100 first, and 100 thereafter.

func WithStacktraceEnabled added in v0.2.0

func WithStacktraceEnabled(enabled bool) Option

WithStacktraceEnabled returns an Option that sets whether the stacktrace field is enabled. It's disabled by default.

func WithStacktraceKey added in v0.2.0

func WithStacktraceKey(key string) Option

WithStacktraceKey returns an Option that sets the stacktrace key. The default value is "stacktrace".

func WithTimeEncoder added in v0.2.0

func WithTimeEncoder(encoder encoding.TimeEncoder) Option

WithTimeEncoder returns an Option that sets the encoder. The default encoding is ISO 8601.

func WithTimeKey added in v0.2.0

func WithTimeKey(key string) Option

WithTimeKey returns an Option that sets the time key. The default value is "time".

func WithWriteSyncer added in v0.2.0

func WithWriteSyncer(ws zapcore.WriteSyncer) Option

WithWriteSyncer returns an Option that sets the underlying writer. The default value is stderr.

Directories

Path Synopsis
Package encoding provides named encoders with flag integration.
Package encoding provides named encoders with flag integration.
Package zaprprom provides a Prometheus metrics implementation for zapr.
Package zaprprom provides a Prometheus metrics implementation for zapr.

Jump to

Keyboard shortcuts

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