log

package
v1.17.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2025 License: MIT Imports: 16 Imported by: 15

Documentation

Overview

Package log provides interface for structured loggers and logf (https://github.com/ssgreg/logf) adapter implementation.

Example
cfgData := bytes.NewBuffer([]byte(`
log:
  level: info
  output: file
  file:
    path: my-service-{{starttime}}-{{pid}}.log
    rotation:
      maxsize: 100M
      maxbackups: 10
      compress: false
  error:
    verbosesuffix: _verbose
`))

cfg := Config{}
cfgLoader := config.NewLoader(config.NewViperAdapter())
err := cfgLoader.LoadFromReader(cfgData, config.DataTypeYAML, &cfg) // Use cfgLoader.LoadFromFile() to read from file.
if err != nil {
	log.Fatal(err)
}

logger, cancel := NewLogger(&cfg)
defer cancel()

logger = logger.With(Int("pid", os.Getpid()))
logger.Info("request served", String("request-id", "generatedrequestid"), DurationIn(time.Second, time.Millisecond))
Output:

Index

Examples

Constants

View Source
const (
	DefaultFileRotationMaxSizeBytes = 1024 * 1024 * 250
	MinFileRotationMaxSizeBytes     = 1024 * 1024

	DefaultFileRotationMaxBackups = 10
	MinFileRotationMaxBackups     = 1
)

Default and restriction values.

Variables

View Source
var Any = logf.Any

Any returns a new Filed with the given key and value of any type. Is tries to choose the best way to represent key-value pair as a Field.

View Source
var Bool = logf.Bool

Bool returns a new Field with the given key and bool.

View Source
var Bytes = logf.Bytes

Bytes returns a new Field with the given key and slice of bytes.

View Source
var DefaultMasks = []MaskingRuleConfig{
	{
		Field:   "Authorization",
		Formats: []FieldMaskFormat{FieldMaskFormatHTTPHeader},
	},
	{
		Field:   "password",
		Formats: []FieldMaskFormat{FieldMaskFormatJSON, FieldMaskFormatURLEncoded},
	},
	{
		Field:   "client_secret",
		Formats: []FieldMaskFormat{FieldMaskFormatJSON, FieldMaskFormatURLEncoded},
	},
	{
		Field:   "access_token",
		Formats: []FieldMaskFormat{FieldMaskFormatJSON, FieldMaskFormatURLEncoded},
	},
	{
		Field:   "refresh_token",
		Formats: []FieldMaskFormat{FieldMaskFormatJSON, FieldMaskFormatURLEncoded},
	},
	{
		Field:   "id_token",
		Formats: []FieldMaskFormat{FieldMaskFormatJSON, FieldMaskFormatURLEncoded},
	},
	{
		Field:   "assertion",
		Formats: []FieldMaskFormat{FieldMaskFormatJSON, FieldMaskFormatURLEncoded},
	},
}
View Source
var Duration = logf.Duration

Duration returns a new Field with the given key and time.Duration.

View Source
var Error = logf.Error

Error returns a new Field with the given error. Key is 'error'.

View Source
var Float32 = logf.Float32

Float32 returns a new Field with the given key and float32.

View Source
var Float64 = logf.Float64

Float64 returns a new Field with the given key and float64.

View Source
var Int = logf.Int

Int returns a new Field with the given key and int.

View Source
var Int16 = logf.Int16

Int16 returns a new Field with the given key and int16.

View Source
var Int32 = logf.Int32

Int32 returns a new Field with the given key and int32.

View Source
var Int64 = logf.Int64

Int64 returns a new Field with the given key and int64.

View Source
var Int8 = logf.Int8

Int8 returns a new Field with the given key and int8.

View Source
var NamedError = logf.NamedError

NamedError returns a new Field with the given key and error.

View Source
var String = logf.String

String returns a new Field with the given key and string.

View Source
var Strings = logf.Strings

Strings returns a new Field with the given key and slice of strings.

View Source
var Time = logf.Time

Time returns a new Field with the given key and time.Time.

View Source
var Uint16 = logf.Uint16

Uint16 returns a new Field with the given key and uint16.

View Source
var Uint32 = logf.Uint32

Uint32 returns a new Field with the given key and uint32.

View Source
var Uint64 = logf.Uint64

Uint64 returns a new Field with the given key and uint64.

View Source
var Uint8 = logf.Uint8

Uint8 returns a new Field with the given key and uint8.

Functions

func NewLogger

func NewLogger(cfg *Config) (FieldLogger, CloseFunc)

NewLogger returns a new logger.

Types

type CloseFunc

type CloseFunc logf.ChannelWriterCloseFunc

CloseFunc allows to close channel writer.

type Config

type Config struct {
	Level   Level            `mapstructure:"level" yaml:"level" json:"level"`
	Format  Format           `mapstructure:"format" yaml:"format" json:"format"`
	Output  Output           `mapstructure:"output" yaml:"output" json:"output"`
	NoColor bool             `mapstructure:"nocolor" yaml:"nocolor" json:"nocolor"`
	File    FileOutputConfig `mapstructure:"file" yaml:"file" json:"file"`

	Error ErrorConfig `mapstructure:"error" yaml:"error" json:"error"`

	// AddCaller determines whether the caller (in package/file:line format) will be added to each logged message.
	//
	// Example of log with caller:
	// 	{"level":"info","time":"...","msg":"starting application HTTP server...","caller":"httpserver/http_server.go:98","address":":8888"}
	AddCaller bool `mapstructure:"addCaller" yaml:"addCaller" json:"addCaller"`

	Masking MaskingConfig `mapstructure:"masking" yaml:"masking" json:"masking"`
	// contains filtered or unexported fields
}

Config represents a set of configuration parameters for logging. Configuration can be loaded in different formats (YAML, JSON) using config.Loader, viper, or with json.Unmarshal/yaml.Unmarshal functions directly.

func NewConfig

func NewConfig(options ...ConfigOption) *Config

NewConfig creates a new instance of the Config.

func NewConfigWithKeyPrefix

func NewConfigWithKeyPrefix(keyPrefix string) *Config

NewConfigWithKeyPrefix creates a new instance of the Config with a key prefix. This prefix will be used by config.Loader. Deprecated: use NewConfig with WithKeyPrefix instead.

func NewDefaultConfig added in v1.11.0

func NewDefaultConfig(options ...ConfigOption) *Config

NewDefaultConfig creates a new instance of the Config with default values.

func (*Config) KeyPrefix

func (c *Config) KeyPrefix() string

KeyPrefix returns a key prefix with which all configuration parameters should be presented. Implements config.KeyPrefixProvider interface.

func (*Config) Set

func (c *Config) Set(dp config.DataProvider) error

Set sets logger configuration values from config.DataProvider. Implements config.Config interface.

func (*Config) SetProviderDefaults

func (c *Config) SetProviderDefaults(dp config.DataProvider)

SetProviderDefaults sets default configuration values for logger in config.DataProvider. Implements config.Config interface.

type ConfigOption added in v1.11.0

type ConfigOption func(*configOptions)

ConfigOption is a type for functional options for the Config.

func WithKeyPrefix added in v1.11.0

func WithKeyPrefix(keyPrefix string) ConfigOption

WithKeyPrefix returns a ConfigOption that sets a key prefix for parsing configuration parameters. This prefix will be used by config.Loader.

type ErrorConfig added in v1.11.0

type ErrorConfig struct {
	// NoVerbose determines whether the verbose error message will be added to each logged error message.
	// If true, or if the verbose error message is equal to the plain error message (err.Error()),
	// no verbose error message will be added.
	// Otherwise, if the logged error implements the fmt.Formatter interface,
	// the verbose error message will be added as a separate field with the key "error" + VerboseSuffix.
	NoVerbose     bool   `mapstructure:"noVerbose" yaml:"noVerbose" json:"noVerbose"`
	VerboseSuffix string `mapstructure:"verboseSuffix" yaml:"verboseSuffix" json:"verboseSuffix"`
}

type Field

type Field = logf.Field

Field hold data of a specific field.

func DurationIn

func DurationIn(val, unit time.Duration) Field

DurationIn returns a new Field with the "duration" as key and received duration in unit as value (int64).

type FieldLogger

type FieldLogger interface {
	With(...Field) FieldLogger

	Debug(string, ...Field)
	Info(string, ...Field)
	Warn(string, ...Field)
	Error(string, ...Field)

	Debugf(string, ...interface{})
	Infof(string, ...interface{})
	Warnf(string, ...interface{})
	Errorf(string, ...interface{})

	AtLevel(Level, func(LogFunc))
	WithLevel(level Level) FieldLogger
}

FieldLogger is an interface for loggers which writes logs in structured format.

func NewDisabledLogger

func NewDisabledLogger() FieldLogger

NewDisabledLogger returns a new logger that logs nothing.

func NewMaskingLogger added in v1.4.0

func NewMaskingLogger(l FieldLogger, r StringMasker) FieldLogger

func NewPrefixedLogger

func NewPrefixedLogger(delegate FieldLogger, prefix string) FieldLogger

NewPrefixedLogger returns a new PrefixedLogger instance.

type FieldMaskFormat added in v1.4.0

type FieldMaskFormat string

FieldMaskFormat defines possible values for field mask formats.

const (
	FieldMaskFormatHTTPHeader FieldMaskFormat = "http_header"
	FieldMaskFormatJSON       FieldMaskFormat = "json"
	FieldMaskFormatURLEncoded FieldMaskFormat = "urlencoded"
)

Field mask formats.

type FieldMasker added in v1.4.0

type FieldMasker struct {
	Field string // Field is a name of a field used in RegExp, must be lowercase
	Masks []Mask
}

FieldMasker is used to mask a field in different formats.

func NewFieldMasker added in v1.4.0

func NewFieldMasker(cfg MaskingRuleConfig) FieldMasker

type FileOutputConfig

type FileOutputConfig struct {
	Path     string             `mapstructure:"path" yaml:"path" json:"path"`
	Rotation FileRotationConfig `mapstructure:"rotation" yaml:"rotation" json:"rotation"`
}

FileOutputConfig is a configuration for file log output.

type FileRotationConfig

type FileRotationConfig struct {
	Compress         bool            `mapstructure:"compress" yaml:"compress" json:"compress"`
	MaxSize          config.ByteSize `mapstructure:"maxSize" yaml:"maxSize" json:"maxSize"`
	MaxBackups       int             `mapstructure:"maxBackups" yaml:"maxBackups" json:"maxBackups"`
	MaxAgeDays       int             `mapstructure:"maxAgeDays" yaml:"maxAgeDays" json:"maxAgeDays"`
	LocalTimeInNames bool            `mapstructure:"localTimeInNames" yaml:"localTimeInNames" json:"localTimeInNames"`
}

FileRotationConfig is a configuration for file log rotation.

type Format

type Format string

Format defines possible values for log formats.

const (
	FormatJSON Format = "json"
	FormatText Format = "text"
)

Logging formats.

type Level

type Level string

Level defines possible values for log levels.

const (
	LevelError Level = "error"
	LevelWarn  Level = "warn"
	LevelInfo  Level = "info"
	LevelDebug Level = "debug"
)

Logging levels.

type LogFunc

type LogFunc = logf.LogFunc

LogFunc allows logging a message with a bound level. nolint: revive

type LogfAdapter

type LogfAdapter struct {
	Logger *logf.Logger
}

LogfAdapter adapts logf.Logger to FieldLogger interface.

func (*LogfAdapter) AtLevel

func (l *LogfAdapter) AtLevel(level Level, fn func(logFunc LogFunc))

AtLevel calls the given fn if logging a message at the specified level is enabled, passing a LogFunc with the bound level.

func (*LogfAdapter) Debug

func (l *LogfAdapter) Debug(s string, fields ...Field)

Debug logs message at "debug" level.

func (*LogfAdapter) Debugf

func (l *LogfAdapter) Debugf(format string, args ...interface{})

Debugf logs a formatted message at "debug" level.

func (*LogfAdapter) Error

func (l *LogfAdapter) Error(s string, fields ...Field)

Error logs message at "error" level.

func (*LogfAdapter) Errorf

func (l *LogfAdapter) Errorf(format string, args ...interface{})

Errorf logs a formatted message at "error" level.

func (*LogfAdapter) Info

func (l *LogfAdapter) Info(s string, fields ...Field)

Info logs message at "info" level.

func (*LogfAdapter) Infof

func (l *LogfAdapter) Infof(format string, args ...interface{})

Infof logs a formatted message at "info" level.

func (*LogfAdapter) Warn

func (l *LogfAdapter) Warn(s string, fields ...Field)

Warn logs message at "warn" level.

func (*LogfAdapter) Warnf

func (l *LogfAdapter) Warnf(format string, args ...interface{})

Warnf logs a formatted message at "warn" level.

func (*LogfAdapter) With

func (l *LogfAdapter) With(fs ...Field) FieldLogger

With returns a new logger with the given additional fields.

func (*LogfAdapter) WithLevel

func (l *LogfAdapter) WithLevel(level Level) FieldLogger

WithLevel returns a new logger with additional level check. All log messages below ("debug" is a minimal level, "error" - maximal) the given AND previously set level will be ignored (i.e. it makes sense to only increase level).

type Mask added in v1.4.0

type Mask struct {
	RegExp *regexp.Regexp
	Mask   string
}

Mask is used to mask a secret in strings.

func NewMask added in v1.4.0

func NewMask(cfg MaskConfig) Mask

type MaskConfig added in v1.4.0

type MaskConfig struct {
	RegExp string `mapstructure:"regexp" yaml:"regexp" json:"regexp"`
	Mask   string `mapstructure:"mask" yaml:"mask" json:"mask"`
}

MaskConfig is a configuration for a single mask.

type Masker added in v1.4.0

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

Masker uses the Aho-Corasick algorithm to simultaneously search for all patterns in a string. The order of applying masking rules is guaranteed.

func NewMasker added in v1.4.0

func NewMasker(rules []MaskingRuleConfig) *Masker

NewMasker creates a new Masker instance. This function initializes two mappings without memory barriers because we are confident that the function has "happens-before" guarantee. Otherwise, we would need to use redundant mutex operations in Mask().

func (*Masker) Mask added in v1.4.0

func (r *Masker) Mask(s string) string

Mask applies the appropriate masking function to the input string.

type MaskingConfig added in v1.4.0

type MaskingConfig struct {
	Enabled         bool                `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
	UseDefaultRules bool                `mapstructure:"useDefaultRules" yaml:"useDefaultRules" json:"useDefaultRules"`
	Rules           []MaskingRuleConfig `mapstructure:"rules" yaml:"rules" json:"rules"`
}

MaskingConfig is a configuration for log field masking.

type MaskingLogger added in v1.4.0

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

MaskingLogger is a logger that masks secrets in log fields. Use it to make sure secrets are not leaked in logs: - If you dump HTTP requests and responses in debug mode. - If a secret is passed via URL (like &api_key=<secret>), network connectivity error will leak it.

func (MaskingLogger) AtLevel added in v1.4.0

func (l MaskingLogger) AtLevel(level Level, fn func(logFunc LogFunc))

AtLevel calls the given fn if logging a Message at the specified level is enabled, passing a LogFunc with the bound level.

func (MaskingLogger) Debug added in v1.4.0

func (l MaskingLogger) Debug(text string, fs ...Field)

Debug logs a formatted Message at "debug" level.

func (MaskingLogger) Debugf added in v1.4.0

func (l MaskingLogger) Debugf(format string, args ...interface{})

Debugf logs a formatted Message at "debug" level.

func (MaskingLogger) Error added in v1.4.0

func (l MaskingLogger) Error(text string, fs ...Field)

Error logs a formatted Message at "error" level.

func (MaskingLogger) Errorf added in v1.4.0

func (l MaskingLogger) Errorf(format string, args ...interface{})

Errorf logs a formatted Message at "error" level.

func (MaskingLogger) Info added in v1.4.0

func (l MaskingLogger) Info(text string, fs ...Field)

Info logs a formatted Message at "info" level.

func (MaskingLogger) Infof added in v1.4.0

func (l MaskingLogger) Infof(format string, args ...interface{})

Infof logs a formatted Message at "info" level.

func (MaskingLogger) Warn added in v1.4.0

func (l MaskingLogger) Warn(text string, fs ...Field)

Warn logs a formatted Message at "warn" level.

func (MaskingLogger) Warnf added in v1.4.0

func (l MaskingLogger) Warnf(format string, args ...interface{})

Warnf logs a formatted Message at "warn" level.

func (MaskingLogger) With added in v1.4.0

func (l MaskingLogger) With(fs ...Field) FieldLogger

With returns a new logger with the given additional fields.

func (MaskingLogger) WithLevel added in v1.4.0

func (l MaskingLogger) WithLevel(level Level) FieldLogger

WithLevel returns a new logger with additional level check. All log messages below ("debug" is a minimal level, "error" - maximal) the given AND previously set level will be ignored (i.e. it makes sense to only increase level).

type MaskingRuleConfig added in v1.4.0

type MaskingRuleConfig struct {
	Field   string            `mapstructure:"field" yaml:"field" json:"field"`
	Formats []FieldMaskFormat `mapstructure:"formats" yaml:"formats" json:"formats"`
	Masks   []MaskConfig      `mapstructure:"masks" yaml:"masks" json:"masks"`
}

MaskingRuleConfig is a configuration for a single masking rule.

type Output

type Output string

Output defines possible values for log outputs.

const (
	OutputStdout Output = "stdout"
	OutputStderr Output = "stderr"
	OutputFile   Output = "file"
)

Logging outputs.

type PrefixedLogger

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

PrefixedLogger represents a logger that prefixes all logging messages with a specific text.

func (*PrefixedLogger) AtLevel

func (l *PrefixedLogger) AtLevel(level Level, fn func(logFunc LogFunc))

AtLevel calls the given fn if logging a message at the specified level is enabled, passing a LogFunc with the bound level.

func (*PrefixedLogger) Debug

func (l *PrefixedLogger) Debug(text string, fs ...Field)

Debug logs a formatted message at "debug" level.

func (*PrefixedLogger) Debugf

func (l *PrefixedLogger) Debugf(format string, args ...interface{})

Debugf logs a formatted message at "debug" level.

func (*PrefixedLogger) Error

func (l *PrefixedLogger) Error(text string, fs ...Field)

Error logs a formatted message at "error" level.

func (*PrefixedLogger) Errorf

func (l *PrefixedLogger) Errorf(format string, args ...interface{})

Errorf logs a formatted message at "error" level.

func (*PrefixedLogger) Info

func (l *PrefixedLogger) Info(text string, fs ...Field)

Info logs a formatted message at "info" level.

func (*PrefixedLogger) Infof

func (l *PrefixedLogger) Infof(format string, args ...interface{})

Infof logs a formatted message at "info" level.

func (*PrefixedLogger) Warn

func (l *PrefixedLogger) Warn(text string, fs ...Field)

Warn logs a formatted message at "warn" level.

func (*PrefixedLogger) Warnf

func (l *PrefixedLogger) Warnf(format string, args ...interface{})

Warnf logs a formatted message at "warn" level.

func (*PrefixedLogger) With

func (l *PrefixedLogger) With(fs ...Field) FieldLogger

With returns a new logger with the given additional fields.

func (*PrefixedLogger) WithLevel

func (l *PrefixedLogger) WithLevel(level Level) FieldLogger

WithLevel returns a new logger with additional level check. All log messages below ("debug" is a minimal level, "error" - maximal) the given AND previously set level will be ignored (i.e. it makes sense to only increase level).

type StringMasker added in v1.4.0

type StringMasker interface {
	Mask(s string) string
}

Directories

Path Synopsis
Package logtest provides implementation of log.FieldLogger that allows writing tests for logging functionality.
Package logtest provides implementation of log.FieldLogger that allows writing tests for logging functionality.

Jump to

Keyboard shortcuts

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