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 ¶
- Constants
- Variables
- func NewLogger(cfg *Config) (FieldLogger, CloseFunc)
- type CloseFunc
- type Config
- type ConfigOption
- type ErrorConfig
- type Field
- type FieldLogger
- type FieldMaskFormat
- type FieldMasker
- type FileOutputConfig
- type FileRotationConfig
- type Format
- type Level
- type LogFunc
- type LogfAdapter
- func (l *LogfAdapter) AtLevel(level Level, fn func(logFunc LogFunc))
- func (l *LogfAdapter) Debug(s string, fields ...Field)
- func (l *LogfAdapter) Debugf(format string, args ...interface{})
- func (l *LogfAdapter) Error(s string, fields ...Field)
- func (l *LogfAdapter) Errorf(format string, args ...interface{})
- func (l *LogfAdapter) Info(s string, fields ...Field)
- func (l *LogfAdapter) Infof(format string, args ...interface{})
- func (l *LogfAdapter) Warn(s string, fields ...Field)
- func (l *LogfAdapter) Warnf(format string, args ...interface{})
- func (l *LogfAdapter) With(fs ...Field) FieldLogger
- func (l *LogfAdapter) WithLevel(level Level) FieldLogger
- type Mask
- type MaskConfig
- type Masker
- type MaskingConfig
- type MaskingLogger
- func (l MaskingLogger) AtLevel(level Level, fn func(logFunc LogFunc))
- func (l MaskingLogger) Debug(text string, fs ...Field)
- func (l MaskingLogger) Debugf(format string, args ...interface{})
- func (l MaskingLogger) Error(text string, fs ...Field)
- func (l MaskingLogger) Errorf(format string, args ...interface{})
- func (l MaskingLogger) Info(text string, fs ...Field)
- func (l MaskingLogger) Infof(format string, args ...interface{})
- func (l MaskingLogger) Warn(text string, fs ...Field)
- func (l MaskingLogger) Warnf(format string, args ...interface{})
- func (l MaskingLogger) With(fs ...Field) FieldLogger
- func (l MaskingLogger) WithLevel(level Level) FieldLogger
- type MaskingRuleConfig
- type Output
- type PrefixedLogger
- func (l *PrefixedLogger) AtLevel(level Level, fn func(logFunc LogFunc))
- func (l *PrefixedLogger) Debug(text string, fs ...Field)
- func (l *PrefixedLogger) Debugf(format string, args ...interface{})
- func (l *PrefixedLogger) Error(text string, fs ...Field)
- func (l *PrefixedLogger) Errorf(format string, args ...interface{})
- func (l *PrefixedLogger) Info(text string, fs ...Field)
- func (l *PrefixedLogger) Infof(format string, args ...interface{})
- func (l *PrefixedLogger) Warn(text string, fs ...Field)
- func (l *PrefixedLogger) Warnf(format string, args ...interface{})
- func (l *PrefixedLogger) With(fs ...Field) FieldLogger
- func (l *PrefixedLogger) WithLevel(level Level) FieldLogger
- type StringMasker
Examples ¶
Constants ¶
const ( DefaultFileRotationMaxSizeBytes = 1024 * 1024 * 250 MinFileRotationMaxSizeBytes = 1024 * 1024 DefaultFileRotationMaxBackups = 10 MinFileRotationMaxBackups = 1 )
Default and restriction values.
Variables ¶
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.
var Bool = logf.Bool
Bool returns a new Field with the given key and bool.
var Bytes = logf.Bytes
Bytes returns a new Field with the given key and slice of bytes.
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}, }, }
var Duration = logf.Duration
Duration returns a new Field with the given key and time.Duration.
var Error = logf.Error
Error returns a new Field with the given error. Key is 'error'.
var Float32 = logf.Float32
Float32 returns a new Field with the given key and float32.
var Float64 = logf.Float64
Float64 returns a new Field with the given key and float64.
var Int = logf.Int
Int returns a new Field with the given key and int.
var Int16 = logf.Int16
Int16 returns a new Field with the given key and int16.
var Int32 = logf.Int32
Int32 returns a new Field with the given key and int32.
var Int64 = logf.Int64
Int64 returns a new Field with the given key and int64.
var Int8 = logf.Int8
Int8 returns a new Field with the given key and int8.
var NamedError = logf.NamedError
NamedError returns a new Field with the given key and error.
var String = logf.String
String returns a new Field with the given key and string.
var Strings = logf.Strings
Strings returns a new Field with the given key and slice of strings.
var Time = logf.Time
Time returns a new Field with the given key and time.Time.
var Uint16 = logf.Uint16
Uint16 returns a new Field with the given key and uint16.
var Uint32 = logf.Uint32
Uint32 returns a new Field with the given key and uint32.
var Uint64 = logf.Uint64
Uint64 returns a new Field with the given key and uint64.
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 ¶
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 ¶
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 ¶
Field hold data of a specific field.
func DurationIn ¶
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 LogfAdapter ¶
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
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().
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 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).