sallust

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2023 License: Apache-2.0 Imports: 16 Imported by: 41

README

sallust

Brings together structured logging, file management, and DI-friendly configuration.

Build Status codecov.io Go Report Card Quality Gate Status Apache V2 License GitHub Release GoDoc

Documentation

Overview

Package sallust adds a few useful features around the go.uber.org/zap package:

- log rotation - path expansion using environment variables - unmarshal-friendly configuration - bootstrapping logging for a go.uber.org/fx application

Index

Constants

View Source
const (
	// DefaultMessageKey is the default value for EncoderConfig.MessageKey.  This value
	// is not used if EncoderConfig.DisableDefaultKeys is true.
	DefaultMessageKey = "msg"

	// DefaultLevelKey is the default value for EncoderConfig.LevelKey.  This value
	// is not used if EncoderConfig.DisableDefaultKeys is true.
	DefaultLevelKey = "level"

	// DefaultTimeKey is the default value for EncoderConfig.TimeKey.  This value
	// is not used if EncoderConfig.DisableDefaultKeys is true.
	DefaultTimeKey = "ts"

	// DefaultNameKey is the default value for EncoderConfig.NameKey.  This value
	// is not used if EncoderConfig.DisableDefaultKeys is true.
	DefaultNameKey = "name"

	// Stdout is the reserved zap output path name that corresponds to stdout.
	Stdout = "stdout"

	// Stderr is the reserved zap output path name that corresponds to stderr.
	Stderr = "stderr"
)
View Source
const (
	// LumberjackScheme is the URL Scheme for lumberjack-rotatable files
	LumberjackScheme = "lumberjack"

	// MaxSizeParameter is the URL parameter that corresponds to lumberjack.Logger.MaxSize
	MaxSizeParameter = "maxSize"

	// MaxAgeParameter is the URL parameter that corresponds to lumberjack.Logger.MaxAge
	MaxAgeParameter = "maxAge"

	// MaxBackupsParameter is the URL parameter that corresponds to lumberjack.Logger.MaxBackups
	MaxBackupsParameter = "maxBackups"

	// LocalTimeParameter is the URL parameter that corresponds to lumberjack.Logger.LocalTime
	LocalTimeParameter = "localTime"

	// CompressParameter is the URL parameter that corresponds to lumberjack.Logger.Compress
	CompressParameter = "compress"
)

Variables

View Source
var (
	// ErrInvalidPermissions is returned by ParsePermissions to indicate a bad permissions value.
	ErrInvalidPermissions = errors.New("Invalid permissions")
)

Functions

func ApplyTransform

func ApplyTransform(transformer func(string) (string, error), paths ...string) (transformed []string, err error)

ApplyTransform transforms each of a set of paths using the supplied strategy. The transformer parameter can be PathTransformer.Transform, or a custom closure. This function always returns a newly allocated slice, even if no transformations are done. Any error interrupts the transformation, and the transformed slice's contents are undefined.

func DecodeHook added in v0.1.2

func DecodeHook(from, to reflect.Type, src interface{}) (interface{}, error)

DecodeHook is an all-in-one mapstructure DecodeHookFunc that converts from a string (typically unmarshaled in something like spf13/viper) into the appropriate configuration field required by zapcore.

The from type must refer exactly to a string, not to a type derived from string.

The to type may be one of:

zapcore.Level
*zapcore.Level
zap.AtomicLevel
*zap.AtomicLevel
zapcore.LevelEncoder
zapcore.TimeEncoder
zapcore.DurationEncoder
zapcore.CallerEncoder
zapcore.NameEncoder

The UnmarshalText method of the to type is used to do the conversion.

Any other from or to type will cause the function to do no conversion and return the src as is with no error.

func Default

func Default() *zap.Logger

Default returns the default zap.Logger used when no logger is found in a context.

func Get

func Get(ctx context.Context) *zap.Logger

Get returns the zap.Logger from the given context. If no zap.Logger exists, this function returns Default().

See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Logger See: https://pkg.go.dev/go.uber.org/zap?tab=doc#NewNop

func GetDefault

func GetDefault(ctx context.Context, def *zap.Logger) *zap.Logger

GetDefault attempts to find a zap.Logger in the given context. If none is found, the given default is returned. If the given default is nil, then Default() is returned instead.

See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Logger

func NewLumberjackSink

func NewLumberjackSink(u *url.URL) (zap.Sink, error)

NewLumberjackSink creates a zap.Sink which rotates its corresponding file. This packages registers this a factory with zap.RegisterSink.

func NewServerLogger added in v0.2.0

func NewServerLogger(serverName string, logger *zap.Logger) *log.Logger

NewServerLogger creates a new zap.Logger appropriate for http.Server.ErrorLog

func NewTestLogger added in v0.2.0

func NewTestLogger(level zapcore.Level) (*bytes.Buffer, *zap.Logger)

func ParsePermissions added in v0.2.2

func ParsePermissions(v string) (perms fs.FileMode, err error)

ParsePermissions parses a nix-style file permissions value. The value must be a 3-digit octal integer with an optional leading zero (0). The empty string is considered to be 000.

func SyncOnShutdown added in v0.1.6

func SyncOnShutdown() fx.Option

SyncOnShutdown adds an fx lifecycle hook that invokes Sync on the application's logger. Generally, this option should be placed as an fx.Invoke last in the set of options. That ensures that log entries from other lifecycle OnStop hooks are written to log sinks.

fx.New(
  // all other options come first ...

  sallust.SyncOnShutdown(),
)

func With

func With(parent context.Context, logger *zap.Logger) context.Context

With places a zap.Logger into the context. If the given logger is nil, this function returns the parent as-is. Since the Get functions return a nop logger when there is no logger in the context, a nil logger can be safely ignored.

See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Logger

func WithLogger added in v0.1.6

func WithLogger(options ...zap.Option) fx.Option

WithLogger bootstraps a go.uber.org/zap logger together with an fxevent.Logger, using the dependencies described in LoggerIn.

If any zap.Options are supplied to this function, they take precedence over any options injected via LoggerIn.

Types

type Config added in v0.1.1

type Config struct {
	// Level is the log level, which is converted to a zap.AtomicLevel.  If unset,
	// info level is assumed.
	Level string `json:"level" yaml:"level"`

	// Development corresponds to zap.Config.Development
	Development bool `json:"development" yaml:"development"`

	// DisableCaller corresponds to zap.Config.DisableCaller
	DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`

	// DisableStacktrace corresponds to zap.Config.DisableStacktrace
	DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`

	// Sampling corresponds to zap.Config.Sampling.  No custom type is necessary
	// here because zap.SamplingConfig uses primitive types.
	Sampling *zap.SamplingConfig `json:"samplingConfig" yaml:"samplingConfig"`

	// Encoding corresponds to zap.Config.Encoding.  If this is unset, and if Development
	// is false, "json" is used.  "console" is the other built-in value for this field,
	// and other encodings can be registered via the zap package.
	//
	// See: https://pkg.go.dev/go.uber.org/zap#RegisterEncoder
	Encoding string `json:"encoding" yaml:"encoding"`

	// EncoderConfig corresponds to zap.Config.EncoderConfig.  A custom type is used
	// here to make integration with libraries like spf13/viper much easier.
	EncoderConfig EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"`

	// OutputPaths are the set of sinks for log output.  This field corresponds to
	// zap.Config.OutputPaths.  If unset, all logging output is discarded.  There is
	// no default for this field.
	//
	// Each output path will have environment variable references expanded unless
	// DisablePathExpansion is true.
	//
	// If Rotation is set, then each output path that is a system file will undergo
	// log file rotation.
	OutputPaths []string `json:"outputPaths" yaml:"outputPaths"`

	// ErrorOutputPaths are the set of sinks for zap's internal messages.  This field
	// corresponds to zap.Config.ErrorOutputPaths.  If unset, Stderr is assumed.
	//
	// As with OutputPaths, environment variable references in each path are expanded
	// unless DisablePathExpansion is true.
	//
	// If Rotation is set, then each output path that is a system file will undergo
	// log file rota
	ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"`

	// InitialFields corresponds to zap.Config.InitialFields.  Note that when unmarshaling
	// from spf13/viper, all keys in this map will be lowercased.
	//
	// Any fields set here will be set on all loggers derived from this configuration.
	InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"`

	// DisablePathExpansion controls whether the paths in OutputPaths and ErrorOutputPaths
	// are expanded.  If this field is set to true, Mapping is ignored and no
	// expansion, even with environment variables, is performed.
	DisablePathExpansion bool `json:"disablePathExpansion" yaml:"disablePathExpansion"`

	// Permissions is the optional nix-style file permissions to use when creating log files.
	// If supplied, this value must be parseable via ParsePermissions.  If this field is unset,
	// zap and lumberjack will control what permissions new log files have.
	Permissions string `json:"permissions" yaml:"permissions"`

	// Mapping is an optional strategy for expanding variables in output paths.
	// If not supplied, os.Getenv is used.
	Mapping func(string) string `json:"-" yaml:"-"`

	// Rotation describes the set of log file rotation options.  This field is optional,
	// and if unset log files are not rotated.
	Rotation *Rotation `json:"rotation,omitempty" yaml:"rotation,omitempty"`
}

Config describes the set of options for building a single zap.Logger. Most of these fields correspond with zap.Config. Use of this type is optional. It simply provides easier configuration for certain features like log rotation. This type is also easier to use with libraries like spf13/viper, which unmarshal from a map[string]interface{} instead of directly from a file.

A Config instance is converted to a zap.Config by applying certain features, such as log rotation. Ultimately, zap.Config.Build is used to actually construct the logger.

See: https://pkg.go.dev/go.uber.org/zap?tab=doc#Config.Build

func (Config) Build added in v0.1.3

func (c Config) Build(opts ...zap.Option) (l *zap.Logger, err error)

Build behaves similarly to zap.Config.Build. It uses the configuration created by NewZapConfig to build the root logger.

func (Config) NewZapConfig added in v0.1.1

func (c Config) NewZapConfig() (zc zap.Config, err error)

NewZapConfig creates a zap.Config enriched with features from these Options. Primarily, this involves creating lumberjack URLs so that the registered sink will create the appropriate infrastructure to do log file rotation.

This method also enforces the Permissions field. Any output or error path will be created initially with the configured file permissions. This allows both zap's file sink and the custom lumberjack sink in this package to honor custom permissions.

type EncoderConfig added in v0.1.4

type EncoderConfig struct {
	// DisableDefaultKeys disables the convenience defaulting of certain log keys.
	// Useful when you want to turn off one of those keys, but explicitly set the others.
	DisableDefaultKeys bool `json:"disableDefaultKeys" yaml:"disableDefaultKeys"`

	// MessageKey is the logging key for the log message.  If unset and if DisableDefaultKeys is true,
	// messages are not inserted into log output.
	MessageKey string `json:"messageKey" yaml:"messageKey"`

	// LevelKey is the logging key for the log level.  If unset and if DisableDefaultKeys is true,
	// log levels are not inserted into log output.
	LevelKey string `json:"levelKey" yaml:"levelKey"`

	// TimeKey is the logging key for the log timestamp.  If unset and if DisableDefaultKeys is true,
	// timestamps are not inserted into log output.
	TimeKey string `json:"timeKey" yaml:"timeKey"`

	// NameKey is the logging key for the logger name.  If unset and if DisableDefaultKeys is true,
	//	logger names are not inserted into log output.
	NameKey string `json:"nameKey" yaml:"nameKey"`

	// CallerKey is the logging key for the caller of the logging method.  If unset, callers are not
	// inserted into log output.
	//
	// Note that Config.DisableCaller, if set, will also prevent callers in each log record.
	// This difference is that Config.DisableCaller shuts off the code that determines the caller,
	// while this field simply doesn't output the caller even though it may have been computed.
	CallerKey string `json:"callerKey" yaml:"callerKey"`

	// FunctionKey is the logging key for the function which called the logging method.  If unset, functions are not
	// inserted into log output.
	//
	// As with CallerKey, Config.DisableCaller also affects whether functions are output.
	FunctionKey string `json:"functionKey" yaml:"functionKey"`

	// StacktraceKey is the logging key for stacktraces for warn, error, and panics.  If unset,
	// stacktraces are never produced.
	StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"`

	// LineEnding is the US-ASCII string that terminates each log record.  By default,
	// a single '\n' is used.
	LineEnding string `json:"lineEnding" yaml:"lineEnding"`

	// EncodeLevel determines how levels are represented.  If unset, LowercaseLevelEncoder is used.
	//
	// See: https://pkg.go.dev/go.uber.org/zap/zapcore#LowercaseLevelEncoder
	EncodeLevel string `json:"levelEncoder" yaml:"levelEncoder" mapstructure:"levelEncoder"`

	// EncodeTime determines how timestamps are represented.  If unset, RFC3339TimeEncoder is used.
	//
	// See: https://pkg.go.dev/go.uber.org/zap/zapcore#RFC3339TimeEncoder
	EncodeTime string `json:"timeEncoder" yaml:"timeEncoder" mapstructure:"timeEncoder"`

	// EncodeDuration determines how time durations are represented.  If unset,
	// StringDurationEncoder is used.
	//
	// See: https://pkg.go.dev/go.uber.org/zap/zapcore#StringDurationEncoder
	EncodeDuration string `json:"durationEncoder" yaml:"durationEncoder" mapstructure:"durationEncoder"`

	// EncodeCaller determines how callers are represented.  If unset,
	// FullCallerEncoder is used.
	//
	// See: https://pkg.go.dev/go.uber.org/zap/zapcore#FullCallerEncoder
	EncodeCaller string `json:"callerEncoder" yaml:"callerEncoder" mapstructure:"callerEncoder"`

	// EncodeName determines how logger names are represented.  If unset,
	// FullNameEncoder is used.
	//
	// See: https://pkg.go.dev/go.uber.org/zap/zapcore#FullNameEncoder
	EncodeName string `json:"nameEncoder" yaml:"nameEncoder" mapstructure:"nameEncoder"`

	// Configures the field separator used by the console encoder. Defaults
	// to tab.
	ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"`
}

EncoderConfig is an analog to zap.EncoderConfig. This type is friendlier to unmarshaling from maps, as encoding.TextUnmarshaler is not honored in those cases.

See: https://pkg.go.dev/go.uber.org/zap/zapcore#EncoderConfig

func (EncoderConfig) NewZapcoreEncoderConfig added in v0.1.4

func (ec EncoderConfig) NewZapcoreEncoderConfig() (zec zapcore.EncoderConfig, err error)

NewZapcoreEncoderConfig converts this instance into a zapcore.EncoderConfig.

In order to ease configuration of zap, this method implements a few conveniences on the returned zapcore.EncoderConfig:

(1) Each of the EncodeXXX fields is defaulted to a sane value. Leaving them unset does not raise an error.

(2) Several logging key fields are defaulted. This defaulting can be turned off by setting DisableDefaultKeys to true. The fields that are defaulted are: MessageKey, LevelKey, TimeKey, and NameKey. The other logging key fields, such as CallerKey, are not defaulted. It's common to leave them turned off for performance or preference.

This method returns an error, as the various UnmarshalText methods it uses return errors. However, in actual practice this method returns a nil error since zapcore falls back to known defaults for any unrecognized text. This method still checks errors internally, in case zapcore changes in the future.

type LoggerFunc added in v0.2.0

type LoggerFunc func([]zap.Field, *http.Request) []zap.Field

LoggerFunc is a strategy for adding key/value pairs (possibly) based on an HTTP request. Functions of this type must append key/value pairs to the supplied slice and then return the new slice.

type LoggerIn added in v0.1.6

type LoggerIn struct {
	fx.In

	// Config is the sallust configuration for the logger.  This component is optional,
	// and if not supplied a default zap logger will be created.
	Config Config `optional:"true"`

	// Options are the optional zap options, injected from the enclosing fx.App.
	// If supplied, these will be appended to the options supplied directly via WithLogger.
	Options []zap.Option `optional:"true"`
}

LoggerIn describes the dependencies used to bootstrap a zap logger within an fx application.

type Lumberjack

type Lumberjack struct {
	*lumberjack.Logger
}

Lumberjack is a zap.Sink adapter that writes to a lumberjack Logger. This type also implements Rotater.

A Lumberjack is safe for concurrent writes. No additional synchronization is required.

func (Lumberjack) Sync

func (lj Lumberjack) Sync() error

Sync is a nop, and implements zapcore.WriteSyncer

type PathTransformer

type PathTransformer struct {
	// Rotation is the optional log rotation configuration.  If supplied,
	// URLs that refer to filesystem paths are altered to be lumberjack URLs.
	Rotation *Rotation

	// Mapping is an optional expansion function passed to os.Expand.  If supplied,
	// this function is used to expand $var and ${var} elements in paths.
	//
	// Any Mapping is always applied to a path first.
	Mapping func(string) string
}

PathTransformer is a strategy for altering paths to incorporate this package's features.

func (PathTransformer) Transform

func (pt PathTransformer) Transform(path string) (string, error)

Transform alters a path to allow for log rotation and expanded variables. This method may be passed to ApplyTransform.

type Rotater

type Rotater interface {
	Rotate() error
}

Rotater is implemented by objects which can rotate logs

type Rotation

type Rotation struct {
	// MaxSize corresponds to lumberjack.Logger.MaxSize
	MaxSize int `json:"maxsize" yaml:"maxsize"`

	// MaxAge corresponds to lumberjack.Logger.MaxAge
	MaxAge int `json:"maxage" yaml:"maxage"`

	// MaxBackups corresponds to lumberjack.Logger.MaxBackups
	MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

	// LocalTime corresponds to lumberjack.Logger.LocalTime
	LocalTime bool `json:"localtime" yaml:"localtime"`

	// Compress corresponds to lumberjack.Logger.Compress
	Compress bool `json:"compress" yaml:"compress"`
}

Rotation describes the set of configurable options for log file rotation. This configuration, if supplied, is only applied to file outputs.

The fields in this struct correspond exactly to lumberjack.Logger.

See: https://pkg.go.dev/gopkg.in/natefinch/lumberjack.v2?tab=doc#Logger

func (Rotation) AddQueryValues

func (r Rotation) AddQueryValues(v url.Values)

AddQueryValues adds the set of URL query parameters for these Rotation options

func (Rotation) NewURL

func (r Rotation) NewURL(path string) *url.URL

NewURL creates a URL object that represents a lumberjack-rotatable file using this set of Rotation options

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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