log

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

The log package contains convenience functions and some useful data definitions for Uber's zap logger, cf. https://github.com/uber-go/zap.

Index

Constants

View Source
const (
	ContextScopeUnknown     = 0
	ContextScopeHTTPRequest = 1 << iota
	ContextScopeHTTPResponse
)

log-scopes

View Source
const (
	ConfigKeyTimeEncoderInt64Seconds = "int64seconds"
	ConfigKeyTimeEncoderShort        = "short"
)

configuration keys for enhanced encoders

Variables

View Source
var (
	// ContextWithHTTPRequestScopeOption configures the log-context to log requests.
	ContextWithHTTPRequestScopeOption = func(ctx context.Context) context.Context {
		if mode, ok := ctx.Value(ContextKeyScope).(ContextScope); ok {
			return context.WithValue(ctx, ContextKeyScope, mode|ContextScopeHTTPRequest)
		}
		return context.WithValue(ctx, ContextKeyScope, ContextScopeHTTPRequest)
	}

	// ContextWithHTTPResponseScopeOption configures the log-context to log responses.
	ContextWithHTTPResponseScopeOption = func(ctx context.Context) context.Context {
		if mode, ok := ctx.Value(ContextKeyScope).(ContextScope); ok {
			return context.WithValue(ctx, ContextKeyScope, mode|ContextScopeHTTPResponse)
		}
		return context.WithValue(ctx, ContextKeyScope, ContextScopeHTTPResponse)
	}
)
View Source
var CapitalColorLevelEncoderOption = LevelEncoderOption(zapcore.CapitalColorLevelEncoder)

CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color. For example, InfoLevel is serialized to "INFO" and colored blue.

View Source
var CapitalLevelEncoderOption = LevelEncoderOption(zapcore.CapitalLevelEncoder)

CapitalLevelEncoder serializes a Level to an all-caps string. For example, InfoLevel is serialized to "INFO".

View Source
var ConsoleEncodingOption = EncodingOption("console")

ConsoleEncoding sets the config's encoding to "console".

View Source
var ContextKeyScope = &contextKeyScope{}

ContextKeyScope is the log-scope context-key.

View Source
var DisableCallerOption = CallerOption(false)

DisableCallerOption prevents logs to be annotated with the calling function's file name and line number.

View Source
var DisableStacktraceOption = StacktraceOption(false)

DisableStacktrace completely disables automatic stacktrace capturing. By default, stacktraces are captured for WarnLevel and above logs in development and ErrorLevel and above in production.

View Source
var EnableCallerOption = CallerOption(true)

EnableCallerOption enables logs to be annotated with the calling function's file name and line number.

View Source
var EnableStacktraceOption = StacktraceOption(true)

EnableStacktrace enables automatic stacktrace capturing. By default, stacktraces are captured for WarnLevel and above logs in development and ErrorLevel and above in production.

View Source
var EpochInt64SecondsEncoderOption = TimeEncoderOption(EpochInt64SecondsEncoder)

EpochInt64SecondsEncoderOption serializes a time.Time to a int64 number of seconds since the Unix epoch.

View Source
var EpochShortTimeEncoderOption = TimeEncoderOption(EpochShortTimeEncoder)

EpochShortTimeEncoder serializes a time.Time to short time string.

View Source
var ISO8601TimeEncoderOption = TimeEncoderOption(zapcore.ISO8601TimeEncoder)

ISO8601TimeEncoderOption serializes a time.Time to an ISO8601-formatted string with millisecond precision.

View Source
var JSONEncodingOption = EncodingOption("json")

ConsoleEncoding sets the config's encoding to "json".

View Source
var (
	// Levels provide a convenient way to list all supported log level strings.
	Levels = []string{

		zapcore.DebugLevel.String(),
		zapcore.InfoLevel.String(),
		zapcore.WarnLevel.String(),
		zapcore.ErrorLevel.String(),
		zapcore.FatalLevel.String(),
	}
)
View Source
var LowercaseColorLevelEncoderOption = LevelEncoderOption(zapcore.LowercaseColorLevelEncoder)

LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring. For example, InfoLevel is serialized to "info" and colored blue.

View Source
var LowercaseLevelEncoderOption = LevelEncoderOption(zapcore.LowercaseLevelEncoder)

LowercaseLevelEncoder serializes a Level to a lowercase string. For example, InfoLevel is serialized to "info".

View Source
var RFC3339NanoTimeEncoderOption = TimeEncoderOption(zapcore.RFC3339NanoTimeEncoder)

RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted string with nanosecond precision.

View Source
var RFC3339TimeEncoderOption = TimeEncoderOption(zapcore.RFC3339TimeEncoder)

RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string.

View Source
var StringDurationEncoderOption = DurationEncoderOption(zapcore.StringDurationEncoder)

StringDurationEncoderOption serializes a time.Duration using its built-in String method.

Functions

func ContextWithLogConfig added in v0.0.2

func ContextWithLogConfig(ctx context.Context, options ...ContextWithLogConfigOption) context.Context

ContextWithLogConfig

func DevConfig

func DevConfig(options ...Option) zap.Config

DevConfig returns a logger and atomic log level aimed at development environments with a highly opinionated configuration. NOTE this factory function panics if an error occurs.

func EpochInt64SecondsEncoder

func EpochInt64SecondsEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

EpochInt64SecondsEncoder serializes a time.Time to a int64 number of seconds since the Unix epoch.

func EpochShortTimeEncoder

func EpochShortTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

EpochShortTimeEncoder serializes a time.Time to short time string.

func StdConfig

func StdConfig(options ...Option) zap.Config

StdConfig returns a logger and atomic log level aimed at development environments with a highly opinionated configuration. NOTE this factory function panics if an error occurs.

Types

type ConfigWrapper

type ConfigWrapper zap.Config

ConfigWrapper is a simple unmarshaling wrapper of zap's Config structure. Let cfg be a variable of zap.Config, then, admittedly, the rather clumsy way of calling the unmarshaling function would be _ = (*ConfigWrapper)(&tt.cfg).Unmarshal(m) ... deal with it.

func (*ConfigWrapper) UnmarshalHCL added in v0.0.2

func (cw *ConfigWrapper) UnmarshalHCL(ctx *hcl.EvalContext, body hcl.Body) error

UnmarshalHCL processes a HCL configuration and returns a zap.Config and the unparsed remainder of body.

func (*ConfigWrapper) UnmarshalMap added in v0.0.2

func (cw *ConfigWrapper) UnmarshalMap(m map[string]interface{}) error

UnmarshalMap supports unmarshaling a zap logger configuration from a map. This way, in a pre-proccessing step, different configuration file formats can be parsed. Also, enhancements, like new encoders, are processed. Lastly, environment variables are resolved, including an attempt, at ensuring the variable HOSTNAME (not available on every platform), is made.

type ContextScope added in v0.0.2

type ContextScope = int

A ContextScope is a bitfield configuring, which aspects of logging are enabled by way of a log-context.

func ContextLogConfigScope added in v0.0.2

func ContextLogConfigScope(ctx context.Context) ContextScope

ContextLogConfigScope returns the log-scope in a context or ContextScopeUnknown.

type ContextWithLogConfigOption added in v0.0.2

type ContextWithLogConfigOption func(ctx context.Context) context.Context

A ContextWithLogConfigOption allows the log-configuration of a context.

type EncoderConfigWrapper added in v0.0.2

type EncoderConfigWrapper zapcore.EncoderConfig

EncoderConfigWrapper ...

func (*EncoderConfigWrapper) UnmarshalHCL added in v0.0.2

func (ecw *EncoderConfigWrapper) UnmarshalHCL(ctx *hcl.EvalContext, body hcl.Body) error

UnmarshalHCL ...

type LogWriterWrapper added in v0.0.2

type LogWriterWrapper zap.Logger

LogWriterWrapper is a simple io.Writer wrapper of zap's Logger.

func (*LogWriterWrapper) Write added in v0.0.2

func (w *LogWriterWrapper) Write(p []byte) (int, error)

Write implements the io.Writer interface.

type Logger added in v0.0.2

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

Logger wraps zap.Logger to allow modifying the log-level after its initialization.

func DevLogger added in v0.0.2

func DevLogger(options ...Option) Logger

DevLogger returns a reasonable default development logging configuration. See DevConfig for more information.

func StdLogger added in v0.0.2

func StdLogger(options ...Option) Logger

StdLogger returns a reasonable default production logging configuration. See StdConfig for more information.

func (Logger) Named added in v0.0.2

func (lg Logger) Named(name string) Logger

Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func (Logger) SetLevel added in v0.0.2

func (lg Logger) SetLevel(lvl zapcore.Level)

SetLevel alters a logger's logging level.

func (Logger) Sugared added in v0.0.2

func (lg Logger) Sugared() SugaredLogger

Sugared 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) With added in v0.0.2

func (lg Logger) With(fields ...zap.Field) Logger

func (Logger) WithLazy added in v0.0.2

func (lg Logger) WithLazy(fields ...zap.Field) Logger

WithLazy creates a child logger and adds structured context to it lazily.

The fields are evaluated only if the logger is further chained with [With] or is written to with any of the log level methods. Until that occurs, the logger may retain references to objects inside the fields, and logging will reflect the state of an object at the time of logging, not the time of WithLazy().

WithLazy provides a worthwhile performance optimization for contextual loggers when the likelihood of using the child logger is low, such as error paths and rarely taken branches.

Similar to [With], fields added to the child don't affect the parent, and vice versa.

func (Logger) WithOptions added in v0.0.2

func (lg Logger) WithOptions(options ...zap.Option) Logger

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

type Option added in v0.0.2

type Option func(*optionArg)

An Option allows a convenient initialization of a logger's configuration.

func CallerOption added in v0.0.2

func CallerOption(enable bool) Option

CallerOption decides, whether logs are annotated with the calling function's file name and line number. By default, all logs are annotated.

func DurationEncoderOption added in v0.0.2

func DurationEncoderOption(encoder zapcore.DurationEncoder) Option

DurationEncoderOption sets the config's duration encoding.

func EncodingOption added in v0.0.2

func EncodingOption(encoding string) Option

EncodingOption sets the config's encoding.

func FieldsOption added in v0.0.2

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

FieldsOption adds fields to a logger. Any fields that require evaluation (such as Objects) are evaluated upon invocation of With.

func LevelEncoderOption added in v0.0.2

func LevelEncoderOption(encoder zapcore.LevelEncoder) Option

LevelEncoderOption sets the config's level encoding.

func LevelOption added in v0.0.2

func LevelOption(lvl zapcore.Level) Option

LevelOption sets the config's initial log-level.

func OutputPathsOption added in v0.0.2

func OutputPathsOption(paths ...string) Option

OutputPathsOption extends a config's OutputPaths setting.

func StacktraceOption added in v0.0.2

func StacktraceOption(enable bool) Option

StacktraceOption decides, whether automatic stacktrace capturing is enabled. By default, stacktraces are captured for WarnLevel and above logs in development and ErrorLevel and above in production.

func TimeEncoderOption added in v0.0.2

func TimeEncoderOption(encoder zapcore.TimeEncoder) Option

TimeEncoderOption sets the config's time encoding.

func ZapOption added in v0.0.2

func ZapOption(options ...zap.Option) Option

ZapOption adds zap options to the logger build process.

type SugaredLogger added in v0.0.2

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

SugaredLogger ...

func (SugaredLogger) Desugar added in v0.0.2

func (lg 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) Named added in v0.0.2

func (lg SugaredLogger) Named(name string) SugaredLogger

Named adds a sub-scope to the logger's name. See Logger.Named for details.

func (SugaredLogger) With added in v0.0.2

func (lg 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.

Jump to

Keyboard shortcuts

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