logp

package
v0.17.5 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2024 License: Apache-2.0 Imports: 19 Imported by: 941

Documentation

Index

Constants

View Source
const DefaultType = "default"

DefaultType is the default log type. If `log.type` is not defined a log entry is considered of type `DefaultType`. Those log entries should follow the default logging configuration.

View Source
const EventType = "event"

EventType is the type for log entries containing event data. Beats and Elastic-Agent use this with the `typedLoggerCore` to direct those log entries to a different file.

View Source
const TypeKey = "log.type"

TypeKey is the default key to define log types.

Different log types can be handled by different cores, the `typedLoggerCore` allows for choosing a different core based on a key/value pair. TypeKey is the default key for using the typedLoggerCore.

It should be used in conjunction with the defined types on this package.

Variables

View Source
var (
	Any         = zap.Any
	Array       = zap.Array
	Binary      = zap.Binary
	Bool        = zap.Bool
	Bools       = zap.Bools
	ByteString  = zap.ByteString
	ByteStrings = zap.ByteStrings
	Complex64   = zap.Complex64
	Complex64s  = zap.Complex64s
	Complex128  = zap.Complex128
	Complex128s = zap.Complex128s
	Duration    = zap.Duration
	Durations   = zap.Durations
	Error       = zap.Error
	Errors      = zap.Errors
	Float32     = zap.Float32
	Float32s    = zap.Float32s
	Float64     = zap.Float64
	Float64s    = zap.Float64s
	Int         = zap.Int
	Ints        = zap.Ints
	Int8        = zap.Int8
	Int8s       = zap.Int8s
	Int16       = zap.Int16
	Int16s      = zap.Int16s
	Int32       = zap.Int32
	Int32s      = zap.Int32s
	Int64       = zap.Int64
	Int64s      = zap.Int64s
	Namespace   = zap.Namespace
	Reflect     = zap.Reflect
	Stack       = zap.Stack
	String      = zap.String
	Stringer    = zap.Stringer
	Strings     = zap.Strings
	Time        = zap.Time
	Times       = zap.Times
	Uint        = zap.Uint
	Uints       = zap.Uints
	Uint8       = zap.Uint8
	Uint8s      = zap.Uint8s
	Uint16      = zap.Uint16
	Uint16s     = zap.Uint16s
	Uint32      = zap.Uint32
	Uint32s     = zap.Uint32s
	Uint64      = zap.Uint64
	Uint64s     = zap.Uint64s
	Uintptr     = zap.Uintptr
	Uintptrs    = zap.Uintptrs
)

Field types for structured logging. Most fields are lazily marshaled so it is inexpensive to add fields to disabled log statements.

Functions

func Configure

func Configure(cfg Config) error

Configure configures the logp package.

func ConfigureWithCore added in v0.11.0

func ConfigureWithCore(loggerCfg Config, core zapcore.Core) error

ConfigureWithCore configures the global logger to use the passed in core. It is assumed that an output has already been defined with the core and a new one should not be created. The loggerCfg is only used to set selectors and level. This is useful if a part of your code uses logp but the log output is already handled. Normal use cases should use Configure or ConfigureWithOutput.

func ConfigureWithOutputs

func ConfigureWithOutputs(defaultLoggerCfg Config, outputs ...zapcore.Core) error

ConfigureWithOutputs configures the global logger to use an output created from `defaultLoggerCfg` and all the outputs passed by `outputs`. This function needs to be exported because it's used by `logp/configure`

func ConfigureWithTypedOutput added in v0.9.6

func ConfigureWithTypedOutput(defaultLoggerCfg, typedLoggerCfg Config, key, value string, outputs ...zapcore.Core) error

ConfigureWithTypedOutput configures the global logger to use typed outputs.

If a log entry matches the defined key/value, this entry is logged using the core generated from `typedLoggerCfg`, otherwise it will be logged by all cores in `outputs` and the one generated from `defaultLoggerCfg`. Arguments:

  • `defaultLoggerCfg` is used to create a new core that will be the default output from the logger
  • `typedLoggerCfg` is used to create a new output that will only be used when the log entry matches `entry[logKey] = kind`
  • `key` is the key the typed logger will look at
  • `value` is the value compared against the `logKey` entry
  • `outputs` is a list of cores that will be added together with the core generated by `defaultLoggerCfg` as the default output for the loggger.

If `defaultLoggerCfg.toObserver` is true, then `typedLoggerCfg` is ignored and a single sink is used so all logs can be observed.

func ConsoleEncoderConfig

func ConsoleEncoderConfig() zapcore.EncoderConfig

func Critical

func Critical(format string, v ...interface{})

Critical uses fmt.Sprintf to construct and log a message. It's an alias for Error. Deprecated: Use logp.NewLogger.

func Debug

func Debug(selector string, format string, v ...interface{})

Debug uses fmt.Sprintf to construct and log a message. Deprecated: Use logp.NewLogger.

func DevelopmentSetup

func DevelopmentSetup(options ...Option) error

DevelopmentSetup configures the logger in development mode at debug level. By default the output goes to stderr.

func Err

func Err(format string, v ...interface{})

Err uses fmt.Sprintf to construct and log a message. Deprecated: Use logp.NewLogger.

func GetLevel added in v0.2.12

func GetLevel() zapcore.Level

func HasSelector

func HasSelector(selector string) bool

HasSelector returns true if the given selector was explicitly set.

func Info

func Info(format string, v ...interface{})

Info uses fmt.Sprintf to construct and log a message. Deprecated: Use logp.NewLogger.

func IsDebug

func IsDebug(selector string) bool

IsDebug returns true if the given selector would be logged. Deprecated: Use logp.NewLogger.

func JSONEncoderConfig

func JSONEncoderConfig() zapcore.EncoderConfig

func MakeDebug

func MakeDebug(selector string) func(string, ...interface{})

MakeDebug returns a function that logs at debug level. Deprecated: Use logp.NewLogger.

func ObserverLogs

func ObserverLogs() *observer.ObservedLogs

ObserverLogs provides the list of logs generated during the observation process.

func Recover

func Recover(msg string)

Recover stops a panicking goroutine and logs an Error.

func SetLevel added in v0.2.12

func SetLevel(lvl zapcore.Level)

func Sync

func Sync() error

Sync flushes any buffered log entries. Applications should take care to call Sync before exiting.

func SyslogEncoderConfig

func SyslogEncoderConfig() zapcore.EncoderConfig

func TestingSetup

func TestingSetup(options ...Option) error

TestingSetup configures logging by calling DevelopmentSetup if and only if verbose testing is enabled (as in 'go test -v').

func WTF deprecated

func WTF(format string, v ...interface{})

WTF prints the message at PanicLevel and immediately panics with the same message.

Deprecated: Use logp.NewLogger and its Panic or DPanic methods.

func Warn

func Warn(format string, v ...interface{})

Warn uses fmt.Sprintf to construct and log a message. Deprecated: Use logp.NewLogger.

Types

type Config

type Config struct {
	Beat      string   `config:",ignore"`   // Name of the Beat (for default file name).
	Level     Level    `config:"level"`     // Logging level (error, warning, info, debug).
	Selectors []string `config:"selectors"` // Selectors for debug level logging.

	ToStderr   bool `config:"to_stderr" yaml:"to_stderr"`
	ToSyslog   bool `config:"to_syslog" yaml:"to_syslog"`
	ToFiles    bool `config:"to_files" yaml:"to_files"`
	ToEventLog bool `config:"to_eventlog" yaml:"to_eventlog"`

	Files   FileConfig    `config:"files"`
	Metrics MetricsConfig `config:"metrics"`
	// contains filtered or unexported fields
}

Config contains the configuration options for the logger. To create a Config from a common.Config use logp/config.Build.

func DefaultConfig

func DefaultConfig(environment Environment) Config

DefaultConfig returns the default config options for a given environment the Beat is supposed to be run within.

func DefaultEventConfig added in v0.9.6

func DefaultEventConfig(environment Environment) Config

DefaultEventConfig returns the default config options for the event logger in a given environment the Beat is supposed to be run within.

func (Config) LogFilename

func (cfg Config) LogFilename() string

LogFilename returns the base filename to which logs will be written for the "files" log output. If another log output is used, or `logging.files.name` is unspecified, then the beat name will be returned.

type Environment

type Environment int

Environment indicates the environment the logger is supped to be run in. The default logger configuration may be different for different environments.

const (
	// DefaultEnvironment is used if the environment the process runs in is not known.
	DefaultEnvironment Environment = iota

	// SystemdEnvironment indicates that the process is started and managed by systemd.
	SystemdEnvironment

	// ContainerEnvironment indicates that the process is running within a container (docker, k8s, rkt, ...).
	ContainerEnvironment

	// MacOSServiceEnvironment indicates that the process is running as a daemon on macOS (e.g. managed via launchctl).
	MacOSServiceEnvironment

	// WindowsServiceEnvironment indicates the the process is run as a windows service.
	WindowsServiceEnvironment

	// InvalidEnvironment indicates that the environment name given is unknown or invalid.
	InvalidEnvironment
)

func ParseEnvironment

func ParseEnvironment(in string) Environment

ParseEnvironment returns the environment type by name. The parse is case insensitive. InvalidEnvironment is returned if the environment type is unknown.

func (Environment) String

func (v Environment) String() string

String returns the string representation the configured environment

type FileConfig

type FileConfig struct {
	Path            string        `config:"path" yaml:"path"`
	Name            string        `config:"name" yaml:"name"`
	MaxSize         uint          `config:"rotateeverybytes" yaml:"rotateeverybytes" validate:"min=1"`
	MaxBackups      uint          `config:"keepfiles" yaml:"keepfiles" validate:"max=1024"`
	Permissions     uint32        `config:"permissions"`
	Interval        time.Duration `config:"interval"`
	RotateOnStartup bool          `config:"rotateonstartup"`
	RedirectStderr  bool          `config:"redirect_stderr" yaml:"redirect_stderr"`
}

FileConfig contains the configuration options for the file output.

type Level

type Level int8

Level is a logging priority. Higher levels are more important.

const (
	DebugLevel Level = iota - 1
	InfoLevel
	WarnLevel
	ErrorLevel
	CriticalLevel // Critical exists only for config backward compatibility.
)

Logging levels.

func (Level) Enabled

func (l Level) Enabled(level Level) bool

Enabled returns true if given level is enabled.

func (Level) MarshalJSON

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON marshals level in a correct form

func (Level) MarshalYAML

func (l Level) MarshalYAML() (interface{}, error)

MarshalYAML marshals level in a correct form

func (Level) String

func (l Level) String() string

String returns the name of the logging level.

func (*Level) Unpack

func (l *Level) Unpack(str string) error

Unpack unmarshals a level string to a Level. This implements ucfg.StringUnpacker.

func (Level) ZapLevel

func (l Level) ZapLevel() zapcore.Level

ZapLevel returns zap alternative to logp.Level.

type LogOption

type LogOption = zap.Option

LogOption configures a Logger.

type Logger

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

Logger logs messages to the configured output.

func L

func L() *Logger

L returns an unnamed global logger.

func NewInMemory added in v0.9.2

func NewInMemory(selector string, encCfg zapcore.EncoderConfig) (*Logger, *bytes.Buffer)

NewInMemory returns a new in-memory logger along with the buffer to which it logs. It's goroutine safe, but operating directly on the returned buffer is not. This logger is primary intended for short and simple use-cases such as printing the full logs only when an operation fails. encCfg configures the log format, use logp.ConsoleEncoderConfig for console format, logp.JSONEncoderConfig for JSON or any other valid zapcore.EncoderConfig.

func NewLogger

func NewLogger(selector string, options ...LogOption) *Logger

NewLogger returns a new Logger labeled with the name of the selector. This should never be used from any global contexts, otherwise you will receive a no-op Logger. This is because the logp package needs to be initialized first. Instead create new Logger instance that your object reuses. Or if you need to log from a static context then you may use logp.L().Infow(), for example.

func (*Logger) Close added in v0.9.9

func (l *Logger) Close() error

Close closes the underlying logger core/writer.

func (*Logger) Core added in v0.2.15

func (l *Logger) Core() zapcore.Core

Core returns the backend zapcore.Core for the logger.

func (*Logger) DPanic

func (l *Logger) DPanic(args ...interface{})

DPanic uses fmt.Sprint to construct and log a message. In development, the logger then panics.

func (*Logger) DPanicf

func (l *Logger) DPanicf(format string, args ...interface{})

DPanicf uses fmt.Sprintf to log a templated message. In development, the logger then panics.

func (*Logger) DPanicw

func (l *Logger) DPanicw(msg string, keysAndValues ...interface{})

DPanicw logs a message with some additional context. The logger panics only in Development mode. The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

Debug uses fmt.Sprint to construct and log a message.

func (*Logger) Debugf

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

Debugf uses fmt.Sprintf to construct and log a message.

func (*Logger) Debugw

func (l *Logger) Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context. The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

Error uses fmt.Sprint to construct and log a message.

func (*Logger) Errorf

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

Errorf uses fmt.Sprintf to log a templated message.

func (*Logger) Errorw

func (l *Logger) Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context. The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) Fatal

func (l *Logger) Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit(1).

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit(1).

func (*Logger) Fatalw

func (l *Logger) Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit(1). The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

Info uses fmt.Sprint to construct and log a message.

func (*Logger) Infof

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

Infof uses fmt.Sprintf to log a templated message.

func (*Logger) Infow

func (l *Logger) Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context. The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) IsDebug

func (l *Logger) IsDebug() bool

IsDebug checks to see if the given logger is Debug enabled.

func (*Logger) Named

func (l *Logger) Named(name string) *Logger

Named adds a new path segment to the logger's name. Segments are joined by periods.

func (*Logger) Panic

func (l *Logger) Panic(args ...interface{})

Panic uses fmt.Sprint to construct and log a message, then panics.

func (*Logger) Panicf

func (l *Logger) Panicf(format string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message, then panics.

func (*Logger) Panicw

func (l *Logger) Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context, then panics. The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) Recover

func (l *Logger) Recover(msg string)

Recover stops a panicking goroutine and logs an Error.

func (*Logger) Sync

func (l *Logger) Sync() error

Sync syncs the logger.

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

Warn uses fmt.Sprint to construct and log a message.

func (*Logger) Warnf

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

Warnf uses fmt.Sprintf to log a templated message.

func (*Logger) Warnw

func (l *Logger) Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context. The additional context is added in the form of key-value pairs. The optimal way to write the value to the log message will be inferred by the value's type. To explicitly specify a type you can pass a Field such as logp.Stringer.

func (*Logger) With

func (l *Logger) With(args ...interface{}) *Logger

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

func (*Logger) WithOptions

func (l *Logger) WithOptions(options ...LogOption) *Logger

WithOptions returns a clone of l with options applied.

type MetricsConfig

type MetricsConfig struct {
	Enabled bool          `config:"enabled"`
	Period  time.Duration `config:"period"`
}

MetricsConfig contains configuration used by the monitor to output metrics into the logstream.

Currently these options are not used through this object in beats (as monitoring is setup elsewhere).

type Option

type Option func(cfg *Config)

Option configures the logp package behavior.

func ToDiscardOutput

func ToDiscardOutput() Option

ToDiscardOutput configures the logger to write to io.Discard. This is for benchmarking purposes only.

func ToObserverOutput

func ToObserverOutput() Option

ToObserverOutput specifies that the output should be collected in memory so that they can be read by an observer by calling ObserverLogs().

func WithLevel

func WithLevel(level Level) Option

WithLevel specifies the logging level.

func WithSelectors

func WithSelectors(selectors ...string) Option

WithSelectors specifies what debug selectors are enabled. If no selectors are specified then they are all enabled.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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