log

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2024 License: MIT Imports: 11 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))

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 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
	Format  Format
	Output  Output
	NoColor bool
	File    FileOutputConfig

	// ErrorNoVerbose 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" + ErrorVerboseSuffix.
	ErrorNoVerbose     bool
	ErrorVerboseSuffix string

	// 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
	// contains filtered or unexported fields
}

Config represents a set of configuration parameters for logging.

func NewConfig

func NewConfig() *Config

NewConfig creates a new instance of the Config.

func NewConfigWithKeyPrefix

func NewConfigWithKeyPrefix(keyPrefix string) *Config

NewConfigWithKeyPrefix creates a new instance of the Config. Allows to specify key prefix which will be used for parsing configuration parameters.

func (*Config) KeyPrefix

func (c *Config) KeyPrefix() string

KeyPrefix returns a key prefix with which all configuration parameters should be presented.

func (*Config) Set

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

Set sets logger configuration values from config.DataProvider.

func (*Config) SetProviderDefaults

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

SetProviderDefaults sets default configuration values for logger in config.DataProvider.

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 NewPrefixedLogger

func NewPrefixedLogger(delegate FieldLogger, prefix string) FieldLogger

NewPrefixedLogger returns a new PrefixedLogger instance.

type FileOutputConfig

type FileOutputConfig struct {
	Path     string
	Rotation FileRotationConfig
}

FileOutputConfig is a configuration for file log output.

type FileRotationConfig

type FileRotationConfig struct {
	Compress         bool
	MaxSize          uint64
	MaxBackups       int
	MaxAgeDays       int
	LocalTimeInNames bool
}

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 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).

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