log

package
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: May 20, 2025 License: MIT Imports: 11 Imported by: 4

README

Logging Configuration

This package provides a flexible logging configuration system built on top of Uber's zap logging library.

Configuration Options

The logging can be configured through flags or environment variables. Here are all available options:

Basic Configuration
Log Level

Controls the minimum logging level.

  • Flag: --log-level
  • Environment: LOG_LEVEL
  • Values: debug, info, warn, error
  • Default: info
Log Format

Controls the output format of the logs.

  • Flag: --log-format
  • Environment: LOG_FORMAT
  • Values: text, json
  • Default: text
Stack Traces

Controls whether stack traces are included for errors.

  • Flag: --log-enable-stacktrace
  • Environment: LOG_ENABLE_STACKTRACE
  • Values: true, false
  • Default: false
Caller Information

Controls whether to include the caller (file and line) in log entries.

  • Flag: --log-enable-caller
  • Environment: LOG_ENABLE_CALLER
  • Values: true, false
  • Default: false
Output Configuration
Output Paths

Controls where logs are written.

  • Flag: --log-output-paths
  • Environment: LOG_OUTPUT_PATHS
  • Values: Array of paths (e.g., stdout, stderr, /var/log/app.log)
  • Default: stderr
Error Output Paths

Controls where error logs are written.

  • Flag: --log-error-output-paths
  • Environment: LOG_ERROR_OUTPUT_PATHS
  • Values: Array of paths (e.g., stdout, stderr, /var/log/app.error.log)
  • Default: stderr
Sampling Configuration

Controls log sampling to prevent overwhelming output in high-throughput scenarios.

Initial Sample

Number of entries with the same message and level to process before sampling begins.

  • Flag: --log-sampling-initial
  • Environment: LOG_SAMPLING_INITIAL
  • Values: Any positive integer
  • Default: 100
Thereafter Sample

After initial sample, log every Nth message.

  • Flag: --log-sampling-thereafter
  • Environment: LOG_SAMPLING_THEREAFTER
  • Values: Any positive integer
  • Default: 100

Advanced Configuration

Key Names

Configure the keys used in structured logging:

  • Message Key

    • Flag: --log-encoder-message-key
    • Environment: LOG_ENCODER_MESSAGE_KEY
    • Default: msg
  • Level Key

    • Flag: --log-encoder-level-key
    • Environment: LOG_ENCODER_LEVEL_KEY
    • Default: level
  • Time Key

    • Flag: --log-encoder-time-key
    • Environment: LOG_ENCODER_TIME_KEY
    • Default: ts
  • Name Key

    • Flag: --log-encoder-name-key
    • Environment: LOG_ENCODER_NAME_KEY
    • Default: logger
  • Caller Key

    • Flag: --log-encoder-caller-key
    • Environment: LOG_ENCODER_CALLER_KEY
    • Default: caller
  • Function Key

    • Flag: --log-encoder-function-key
    • Environment: LOG_ENCODER_FUNCTION_KEY
    • Default: `` (empty)
  • Stacktrace Key

    • Flag: --log-encoder-stacktrace-key
    • Environment: LOG_ENCODER_STACKTRACE_KEY
    • Default: stacktrace
Encoder Configuration
Level Encoder

Controls how the log level is formatted.

  • Flag: --log-encoder-level-encoder
  • Environment: LOG_ENCODER_LEVEL_ENCODER
  • Values:
    • capital - "INFO", "ERROR"
    • capitalColor - "INFO" (with color)
    • color - "info" (with color)
    • lowercase - "info", "error"
  • Default: capitalColor
Time Encoder

Controls how timestamps are formatted.

  • Flag: --log-encoder-time-encoder
  • Environment: LOG_ENCODER_TIME_ENCODER
  • Values:
    • rfc3339nano - RFC3339 with nanoseconds
    • rfc3339 - RFC3339
    • iso8601 - ISO8601
    • millis - Milliseconds since epoch
    • nanos - Nanoseconds since epoch
    • time - Custom format "2006-01-02T15:04:05.000Z07:00"
  • Default: time
Duration Encoder

Controls how durations are formatted.

  • Flag: --log-encoder-duration-encoder
  • Environment: LOG_ENCODER_DURATION_ENCODER
  • Values:
    • string - Human-readable duration (e.g. "1s")
    • nanos - Nanoseconds as integer
    • ms - Milliseconds as integer
    • s - Seconds as float
  • Default: s
Caller Encoder

Controls how caller information is formatted.

  • Flag: --log-encoder-caller-encoder
  • Environment: LOG_ENCODER_CALLER_ENCODER
  • Values:
    • full - Full file path
    • short - Package name and file
  • Default: short
Name Encoder

Controls how logger names are formatted.

  • Flag: --log-encoder-name-encoder
  • Environment: LOG_ENCODER_NAME_ENCODER
  • Values:
    • full - Full logger name
  • Default: full
Output Formatting
Line Ending
  • Skip Line Ending

    • Flag: --log-encoder-skip-line-ending
    • Environment: LOG_ENCODER_SKIP_LINE_ENDING
    • Values: true, false
    • Default: false
  • Line Ending

    • Flag: --log-encoder-line-ending
    • Environment: LOG_ENCODER_LINE_ENDING
    • Default: \n
Console Separator

Controls the separator used in console output format.

  • Flag: --log-encoder-console-separator
  • Environment: LOG_ENCODER_CONSOLE_SEPARATOR
  • Default: \t (tab)

Example Usage

Using flags:

./myapp --log-level debug --log-format json --log-enable-stacktrace true --log-enable-caller true

Using environment variables:

LOG_LEVEL=debug LOG_FORMAT=json LOG_ENABLE_STACKTRACE=true LOG_ENABLE_CALLER=true ./myapp

Advanced configuration example:

./myapp \
  --log-level debug \
  --log-format json \
  --log-encoder-time-encoder rfc3339nano \
  --log-encoder-level-encoder capitalColor \
  --log-encoder-caller-encoder full \
  --log-encoder-console-separator "  " \
  --log-sampling-initial 100 \
  --log-sampling-thereafter 100 \
  --log-output-paths stdout,/var/log/app.log \
  --log-error-output-paths stderr,/var/log/app.error.log

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFlags

func AddFlags(v *viper.Viper, f *pflag.FlagSet) error

AddFlags adds flags to the given viper and pflag.FlagSet. Sets - all viper keys with "log." prefix - all environment variables with "LOG_" prefix - all flags with "log-" prefix

func LoggerFromContext

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

LoggerFromContext returns a logger from the given context with the default namespace tags attached to it

func LoggerWithFieldsFromContext

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

LoggerWithFieldsFromContext returns a logger from the given context with the default namespace tags attached to it

func LoggerWithFieldsFromNamespaceContext

func LoggerWithFieldsFromNamespaceContext(ctx context.Context, namespaces ...string) *zap.Logger

LoggerWithFieldsFromNamespaceContext returns a logger from the given context. It loads the tags from the provided tags namespace and adds them to the logger.

func TagsToFields

func TagsToFields(tags []*tag.Tag) []zap.Field

TagsToFields converts a slice of tags to zap fields

func WithLogger

func WithLogger(ctx context.Context, logger *zap.Logger) context.Context

WithLogger returns a new context with the given logger attached to it

Types

type CallerEncoder added in v0.2.1

type CallerEncoder int
const (
	CallerEncoderFull CallerEncoder = iota
	CallerEncoderShort
)

func ParseCallerEncoder added in v0.2.1

func ParseCallerEncoder(encoder string) (CallerEncoder, error)

func (CallerEncoder) String added in v0.3.5

func (c CallerEncoder) String() string

type Config added in v0.2.1

type Config struct {
	Format           *Format         `key:"format,omitempty" desc:"Log format"`
	Level            *Level          `key:"level,omitempty" desc:"Minimum enabled logging level"`
	EnableStacktrace *bool           `` /* 127-byte string literal not displayed */
	EnableCaller     *bool           `key:"enable-caller,omitempty" env:"ENABLE_CALLER" flag:"enable-caller" desc:"Enable caller"`
	Encoder          *EncoderConfig  `key:"encoding,omitempty" flag:"encoding" env:"ENCODING" desc:"Encoding: "`
	Sampling         *SamplingConfig `key:"sampling,omitempty" desc:"Sampling: "`
	OutputPaths      *[]*string      `key:"output-paths,omitempty" env:"OUTPUT_PATHS" flag:"output" desc:"List of URLs or file paths to write logging output to"`
	ErrorOutputPaths *[]*string      `` /* 132-byte string literal not displayed */
}

Config is the configuration to create a zap.Config.

func DefaultConfig added in v0.3.5

func DefaultConfig() *Config

DefaultConfig returns a default Config.

func (*Config) Env added in v0.3.5

func (cfg *Config) Env() (map[string]string, error)

Env returns the environment variables for the given Config. All environment variables are prefixed with "LOG_".

func (*Config) Unmarshal added in v0.3.5

func (cfg *Config) Unmarshal(v *viper.Viper) error

Unmarshal unmarshals the given viper into the Config. Assumes - all viper keys are prefixed with "log." - all environment variables are prefixed with "LOG_".

func (*Config) ZapConfig added in v0.3.5

func (cfg *Config) ZapConfig() *zap.Config

type DurationEncoder added in v0.2.1

type DurationEncoder int
const (
	DurationEncoderString DurationEncoder = iota
	DurationEncoderNanos
	DurationEncoderMillis
	DurationEncoderSeconds
)

func ParseDurationEncoder added in v0.2.1

func ParseDurationEncoder(encoder string) (DurationEncoder, error)

func (DurationEncoder) String added in v0.3.5

func (d DurationEncoder) String() string

type EncoderConfig added in v0.2.1

type EncoderConfig struct {
	MessageKey       *string          `` /* 130-byte string literal not displayed */
	LevelKey         *string          `key:"level-key,omitempty" env:"LEVEL_KEY" flag:"level-key" desc:"Key for the log level (if empty, the level is omitted)"`
	TimeKey          *string          `key:"time-key,omitempty" env:"TIME_KEY" flag:"time-key" desc:"Key for the log timestamp (if empty, the timestamp is omitted)"`
	NameKey          *string          `` /* 129-byte string literal not displayed */
	CallerKey        *string          `key:"caller-key,omitempty" env:"CALLER_KEY" flag:"caller-key" desc:"Key for the log caller (if empty, the caller is omitted)"`
	FunctionKey      *string          `` /* 135-byte string literal not displayed */
	StacktraceKey    *string          `` /* 145-byte string literal not displayed */
	SkipLineEnding   *bool            `key:"skip-line-ending,omitempty" env:"SKIP_LINE_ENDING" flag:"skip-line-ending" desc:"Skip the line ending"`
	LineEnding       *string          `key:"line-ending,omitempty" env:"LINE_ENDING" flag:"line-ending" desc:"Line ending"`
	LevelEncoder     *LevelEncoder    `` /* 175-byte string literal not displayed */
	TimeEncoder      *TimeEncoder     `` /* 191-byte string literal not displayed */
	DurationEncoder  *DurationEncoder `` /* 168-byte string literal not displayed */
	CallerEncoder    *CallerEncoder   `` /* 147-byte string literal not displayed */
	NameEncoder      *NameEncoder     `` /* 146-byte string literal not displayed */
	ConsoleSeparator *string          `` /* 133-byte string literal not displayed */
}

func (*EncoderConfig) EncoderConfig added in v0.3.5

func (cfg *EncoderConfig) EncoderConfig() *zapcore.EncoderConfig

type Format

type Format int
const (
	TextFormat Format = iota
	JSONFormat
)

func ParseFormat

func ParseFormat(format string) (Format, error)

func (Format) String added in v0.3.5

func (f Format) String() string

type Level

type Level int
const (
	DebugLevel Level = iota
	InfoLevel
	WarnLevel
	ErrorLevel
)

func ParseLevel

func ParseLevel(level string) (Level, error)

func (Level) String added in v0.3.5

func (l Level) String() string

type LevelEncoder added in v0.2.1

type LevelEncoder int
const (
	LevelEncoderCapital LevelEncoder = iota
	LevelEncoderCapitalColor
	LevelEncoderColor
	LevelEncoderLowercase
)

func ParseLevelEncoder added in v0.2.1

func ParseLevelEncoder(encoder string) (LevelEncoder, error)

func (LevelEncoder) String added in v0.3.5

func (l LevelEncoder) String() string

type NameEncoder added in v0.2.1

type NameEncoder int
const (
	NameEncoderFull NameEncoder = iota
	NameEncoderShort
)

func ParseNameEncoder added in v0.2.1

func ParseNameEncoder(encoder string) (NameEncoder, error)

func (NameEncoder) String added in v0.3.5

func (n NameEncoder) String() string

type SamplingConfig added in v0.2.3

type SamplingConfig struct {
	Initial    *int `key:"initial,omitempty" desc:"Number of log entries with the same level and message to log before dropping entries"`
	Thereafter *int `key:"thereafter,omitempty" desc:"After the initial number of entries, every Mth entry is logged and the rest are dropped"`
}

type TimeEncoder added in v0.2.1

type TimeEncoder int
const (
	TimeEncoderRFC3339Nano TimeEncoder = iota
	TimeEncoderRFC3339
	TimeEncoderISO8601
	TimeEncoderMillis
	TimeEncoderNanos
	TimeEncoderTime
)

func ParseTimeEncoder added in v0.2.1

func ParseTimeEncoder(encoder string) (TimeEncoder, error)

func (TimeEncoder) String added in v0.3.5

func (t TimeEncoder) String() string

Jump to

Keyboard shortcuts

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