Documentation
¶
Index ¶
- Constants
- Variables
- func AtLevel(l Level) func(*MockEntry)
- func ContextWithLogger(ctx context.Context, lg Logger) context.Context
- func EnableTraceLogs(fn func(...any))
- func LogfmtFormatter(opt ...LogfmtOption) func() (Formatter, error)
- func LogtailTransport(opts ...LogtailOption) func() (transport, error)
- func MuxFormat(id string, f FormatterFactory) func(*mux) error
- func NewLogger(ctx context.Context, cfg ...LoggerOption) (Logger, CloseFn, error)
- func NewMock() (Logger, MockLog)
- func RegisterEnrichment(d EnrichmentFunc)
- func WithField(key string) func(*MockEntry)
- func WithFieldValue(k, v string) func(*MockEntry)
- func WithFieldValues(fields map[string]string) func(*MockEntry)
- func WithFields(key string, moreKeys ...string) func(*MockEntry)
- func WithMessage(s string) func(*MockEntry)
- type Batch
- type ByteWriter
- type CloseFn
- type ContextLoggerOption
- type EnrichmentFunc
- type EntryExpectation
- type FieldId
- type Formatter
- type FormatterFactory
- type JSONFormatterOption
- type Level
- type LevelLogger
- type LogfmtOption
- type Logger
- type LoggerOption
- type LogtailOption
- type MockEntry
- type MockLog
- type MsgpackOption
- type MuxOption
- type StdioTransportOption
- type TargetOption
- type TransportFactory
Constants ¶
const ( // NoopIfNotPresent is a ContextLoggerOption that specifies that if no logger is // present in the context, a no-op logger should be returned; this is also // the default behavior if no ContextLoggerOption is supplied. // // The caller can safely emit logs without checking for the presence // of a logger. NoopIfNotPresent = ContextLoggerOption(0) // PanicIfNotPresent is a ContextLoggerOption that specifies that if no logger is // present in the context, a panic should occur (ErrNoLoggerInContext). PanicIfNotPresent = ContextLoggerOption(1) // NilIfNotPresent is a ContextLoggerOption that specifies that if no logger is // present in the context, nil should be returned. It is then the // responsibility of the caller to handle the absence of a logger. NilIfNotPresent = ContextLoggerOption(2) )
const Required = PanicIfNotPresent
Required is equivalent to PanicIfNotPresent.
Deprecated: new code should use PanicIfNotPresent.
Variables ¶
var ( ErrBackendNotConfigured = errors.New("a backend must be configured first") ErrFormatAlreadyRegistered = errors.New("a format with this id is already registered") ErrInvalidConfiguration = errors.New("invalid configuration") ErrInvalidFormatReference = errors.New("invalid type for format; must be a Formatter or the (string) id of a Formatter previously added to the mux") ErrKeyNotSupported = errors.New("key not supported") ErrLogtailConfiguration = errors.New("logtail transport configuration") ErrNoLoggerInContext = errors.New("no logger in context") ErrNotImplemented = errors.New("not implemented") ErrUnknownFormat = errors.New("unknown format") // errors returns by the mock listener when expectations are not met ErrExpectationsNotMet = errors.New("expectations were not met") ErrMalformedLogEntry = errors.New("log entry did not meet expectations") ErrMissingExpectedLogEntry = errors.New("missing an expected log entry") ErrUnexpectedLogEntry = errors.New("unexpected log entry") )
var ExitFn func(int) = os.Exit
ExitFn is a func var allowing `ulog` code paths that reach an `os.Exit` call to be replaced by a non-exiting behaviour.
This is primarily used in `ulog` unit tests but also allows (e.g.) a microservice to intercept exit calls and perform a controlled exit, even when a log call results in termination of the microservice.
var Levels = []Level{TraceLevel, DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel}
Functions ¶
func AtLevel ¶ added in v0.2.0
AtLevel returns a function that sets the expected log level of an entry.
func ContextWithLogger ¶
returns a new context with the supplied logger added to it.
The supplied logger will be enriched with the context to avoid incurring this encrichment every time the logger is retrieved from the context (if the context is further enriched, the logger
then a new
).
Example:
ctx := ulog.ContextWithLogger(ctx, logger)
func EnableTraceLogs ¶ added in v0.4.0
func EnableTraceLogs(fn func(...any))
func LogfmtFormatter ¶ added in v0.2.0
func LogfmtFormatter(opt ...LogfmtOption) func() (Formatter, error)
LogfmtFormatter configures a logfmt formatter to format entries in the logfmt format:
The default formatter will produce output similar to:
time=2006-01-02T15:04:05.000000Z level=INFO message="some logged message"
Configuration options are provided to allow the default labels and values for the level field:
LogfmtLabels() may be used to configure the labels used for each of the core fields in an entry: TimestampField, LevelField, MessageField. The order of the fields is fixed and cannot be changed.
LogfmtLevels() may be used to configure the values used for the LevelField value.
func LogtailTransport ¶ added in v0.2.0
func LogtailTransport(opts ...LogtailOption) func() (transport, error)
LogtailTransport returns a transport factory function to create and configure a LogtailTransport transport with specified configuration options applied.
func MuxFormat ¶ added in v0.2.0
func MuxFormat(id string, f FormatterFactory) func(*mux) error
MuxFormat registers a Formatter with the mux, with a specified id. The id must be unique within the mux.
A Formatter added to the mux may be shared by multiple targets by specifying a TargetFormat(id) option with the same id as the Formatter. The Formatter must already have been added to the mux before it can be referenced by a target.
A Formatter that is not shared by multiple targets does not need to be added to the mux separately; a target-specific Formatter may be configured directly using the TargetFormat(Formatter) option for the relevant target.
func NewLogger ¶
NewLogger returns a new logger with the given configuration options applied and a close function that must be called to cleanly shutdown the logger and ensure that log entries are not lost.
If there are any errors in the configuration, a nil logger is returned along with the error. In this situation, the close function returned is a no-op; it is safe to call it, immediately or deferred.
If the logger is configured without a backend, a stdio backend will be used with a logfmt formatter and os.Stdout as the output.
If no Level is configured, the default level is Info.
func NewMock ¶
NewMock returns a logger with a listener that sends log entries to a mock listener implementation.
Unlike other backend factories which are used to configure a Logger initialised by the NewLogger() factory, NewMock() initialises and returns a complete Logger, as well as initialising the backend used by that Logger to configure and test expectations.
func RegisterEnrichment ¶
func RegisterEnrichment(d EnrichmentFunc)
RegisterEnrichment registers a specified function.
func WithField ¶ added in v0.2.0
WithField returns a function that sets an expected field in an entry.
The expectation will match an entry that has the specified field among its fields, regardless of the value of the field.
func WithFieldValue ¶ added in v0.2.0
WithFieldValue returns a function that sets an expected field and value.
The expectation will match an entry if it has, among its fields, the specified field with matching value.
func WithFieldValues ¶ added in v0.2.0
WithFieldValues returns a function that sets expected fields in an entry.
The expectation will match if it has fields that, at a minimum, contain all of the specified fields with values matching those expected.
func WithFields ¶ added in v0.2.0
WithFields returns a function that sets one or more expected fields in an entry.
The expectation will match an entry that has the specified fields among its fields, regardless of the value of those fields.
func WithMessage ¶ added in v0.2.0
WithMessage returns a function that sets an expected message.
The expectation will only match an entry if it has the specified message.
Types ¶
type Batch ¶ added in v0.2.0
type Batch struct {
// contains filtered or unexported fields
}
Batch is a collection of log entries that can be written by a Transport in a single operation.
type ByteWriter ¶
type ByteWriter interface { io.Writer io.ByteWriter }
ByteWriter is an interface that implements both io.Writer and io.ByteWriter
type ContextLoggerOption ¶
type ContextLoggerOption int
ContextLoggerOption values determine the behaviour of ulog.FromContext when no logger is present in the context.
Values ¶
NoopIfNotPresent // a no-op logger will be returned PanicIfNotPresent // a panic will occur (ErrNoLoggerInContext) NilIfNotPresent // nil will be returned
type EnrichmentFunc ¶
EnrichmentFunc provides the signature of a function that may be registered to extract log enrichment fields from a specified Context
An EnrichmentFunc identifies any values in the supplied Context that should be added to the log entry and returns them in the form of a map[string]any of fields (keys) and values.
type EntryExpectation ¶ added in v0.2.0
type EntryExpectation = func(*MockEntry)
EntryExpectation is a function that refines the properties of an expected log entry
type FieldId ¶
type FieldId int
FieldId is the type of a field identifier, providing an id for each standard field in a log entry. "Standard" fields are those that are always present in a log entry (depending on logger configuration).
const ( TimeField FieldId = iota // TimeField is the FieldId of the time field LevelField // LevelKey is the FieldId of the level field MessageField // MessageKey is the FieldId of the message field CallsiteFileField // CallsiteFileField is the FieldId of the file field; used only when call-site logging is enabled CallsiteFunctionField // CallsiteFunctionField is the FieldId of the function field; used only when call-site logging is enabled )
type Formatter ¶
type Formatter interface {
Format(int, entry, ByteWriter)
}
Formatter is an interface implemented by a log formatter
type FormatterFactory ¶
type FormatterFactory = func() (Formatter, error) // FormatterFactory is a function that returns a new Formatter
func JSONFormatter ¶
func JSONFormatter(opt ...JSONFormatterOption) FormatterFactory
NewJSONFormatter returns a function that configures a json formatter.
func MsgpackFormatter ¶ added in v0.2.0
func MsgpackFormatter(opts ...MsgpackOption) FormatterFactory
MsgpackFormatter returns a function that configures a msgpack formatter.
type JSONFormatterOption ¶ added in v0.4.3
type JSONFormatterOption func(*jsonfmt) error // a function for configuring a json formatter
func JSONFieldNames ¶ added in v0.2.0
func JSONFieldNames(keys map[FieldId]string) JSONFormatterOption
LogfmtLabels configures the labels used for the each of the core fields in a logfmt log: time, level, message, file and function.
A map[FieldId]string is used to override the default label for each field that is required; if a field is not included in the map the default label will continue to be used for that field.
The default labels for each field are:
TimeField: time LevelField: level MessageField: message FileField: file FunctionField: function
Although the label for each field may be configured, the inclusion of these fields in a log entry is fixed and cannot be changed, as is the order of the fields in the output.
func JSONLevelLabels ¶ added in v0.2.0
func JSONLevelLabels(levels map[Level]string) JSONFormatterOption
JSONLevelLabels configures the values used for the Level field in json formatted log entries.
type Level ¶
type Level int
Level identifies the logging level for a particular log entry. Possible values, in increasing order of severity (decreasing ordinal value), are:
- TraceLevel (6)
- DebugLevel
- InfoLevel
- WarnLevel
- ErrorLevel
- FatalLevel (1)
const ( FatalLevel Level // FatalLevel indicates a condition that requires the process to terminate; after writing the log ulog.ExitFn is called ErrorLevel // ErrorLevel indicates the log entry relates to an error WarnLevel // WarnLevel indicates the log entry is a warning about some unexpected but recoverable condition InfoLevel // InfoLevel indicates the log entry is an informational message DebugLevel // DebugLevel indicates the log entry is a debug message, typically used during development TraceLevel // TraceLevel indicates the log entry is a trace message, usually to aid in diagnostics )
type LevelLogger ¶
type LevelLogger interface { Log(string) // Log emits a log entry at the level of the LevelLogger Logf(string, ...any) // Logf emits a log entry at the level of the LevelLogger, using a specified format string and args WithField(string, any) LevelLogger // WithField returns a new LevelLogger that will add a specified field to all log entries WithFields(map[string]any) LevelLogger // WithFields returns a new LevelLogger that will add a specified set of fields to all log entries }
LevelLogger is an interface for a logger that is limited to emitting log messages at a specified level.
A LevelLogger is obtained by calling Logger.AtLevel(Level). If the specified level is not enabled on the Logger the returned LevelLogger will be a no-op logger.
Example:
logger := ulog.FromContext(ctx) debug := logger.AtLevel(ulog.DebugLevel) debug.Log("this is a debug message")
type LogfmtOption ¶
type LogfmtOption func(*logfmt) error // LogfmtOption is a function that configures a logfmt formatter
func LogfmtFieldNames ¶ added in v0.2.0
func LogfmtFieldNames(keys map[FieldId]string) LogfmtOption
LogfmtFieldNames configures the labels used for the each of the core fields in a logfmt log entry: time, level and message.
A map[FieldId]string is used to override the default label for each field that is required; if a field is not included in the map, the default label will continue to be used for that field.
The default labels for each field are:
TimeField: time LevelField: level MessageField: message
Although the label for each field may be configured, the inclusion of these fields and their order is fixed, and cannot be changed.
func LogfmtLevelLabels ¶ added in v0.2.0
func LogfmtLevelLabels(levels map[Level]string) LogfmtOption
LogfmtLevelLabels may be used to override the values used for the Level field in logfmt log entries.
A map[Level]string is used to override the default value for each level that is required; for any Level not included in the map, the currently configured value will be left as-is.
The default labels are:
TraceLevel: TRACE DebugLevel: DEBUG InfoLevel: INFO WarnLevel: WARN ErrorLevel: ERROR FatalLevel: FATAL
Values are automatically right-padded with spaces to be of equal length to make it easier to visually parse log entries when reading a log, ensuring that the message part of each entry starts at the same position.
type Logger ¶
type Logger interface { Log(Level, string) // Log emits a log message at a specified level Logf(level Level, format string, args ...any) // Logf emits a log message at a specified level using a specified format string and args Debug(s string) // Debug emits a Debug level log message Debugf(format string, args ...any) // Debugf emits a Debug level log message using a specified format string and args Error(err any) // Error emits an Error level log message consisting of err Errorf(format string, args ...any) // Errorf emits an Error level log message using a specified format string and args Fatal(err any) // Fatal emits a Fatal level log message then calls ExitFn(n) with the current exit code (or 1 if not set) Fatalf(format string, args ...any) // Fatalf emits a Fatal level log message using a specified format string and args, then calls ExitFn(n) with the current exit code (or 1 if not set) Info(s string) // Info emits an Info level log message Infof(format string, args ...any) // Infof emits an Info level log message using a specified format string and args Trace(s string) // Trace emits a Trace level log message Tracef(format string, args ...any) // Tracef emits a Trace level log message using a specified format string and args Warn(s string) // Warn emits a Warn level log message Warnf(format string, args ...any) // Warnf emits a Warn level log message using a specified format string and args AtLevel(Level) LevelLogger // AtLevel returns a new LevelLogger with the same Context and Fields (if any) as those on the receiver Logger WithContext(context.Context) Logger // WithContext returns a new Logger encapsulating the specific Context WithExitCode(int) Logger // WithExitCode returns a new Logger with a specified exit code set WithField(string, any) Logger // WithField returns a new Logger that will add a specified field to all log entries WithFields(map[string]any) Logger // WithFields returns a new Logger that will add a specified set of fields to all log entries }
Logger is the interface used by applications and modules to emit log entries and provide enriched context for logging.
func FromContext ¶
func FromContext(ctx context.Context, opt ...ContextLoggerOption) Logger
FromContext returns any logger present in the supplied Context. The result if no logger is present in the context depends on the value of the (optional) ContextLoggerOption supplied:
NoopIfNotPresent // a no-op logger will be returned PanicIfNotPresent // a panic will occur (ErrNoLoggerInContext) NilIfNotPresent // nil will be returned
0, 1 or many ContextLoggerOption values may be specified:
0 // NoopIfNotPresent is assumed 1 // the specified option is applied >1 // the first specified option is applied
Example:
log := ulog.FromContext(ctx, ulog.Required)
type LoggerOption ¶
type LoggerOption = func(*logger) error
LoggerOption is a function for configuring a logger
func LogCallsite ¶
func LogCallsite(e bool) LoggerOption
LogCallsite returns a function that sets whether or not call site information is included in logs produced by a logger
func LoggerFormat ¶
func LoggerFormat(f FormatterFactory) LoggerOption
LoggerFormat sets the formatter of a logger. This configuration option only makes sense for a non-muxing logger with a backend that supports configurable formatting.
If configured without/before a backend being configured, a stdio backend will be installed using the supplied formatter writing to os.Stdout.
Returns ErrInvalidConfiguration error if configured on a mux logger.
func LoggerLevel ¶
func LoggerLevel(level Level) LoggerOption
LoggerLevel returns a function that sets the log level of a logger
func LoggerOutput ¶
func LoggerOutput(out io.Writer) LoggerOption
LoggerOutput sets the io.Writer of a logger. This configuration option only makes sense for a non-muxing logger.
Returns ErrInvalidConfiguration error if configured on a mux logger.
func Mux ¶
func Mux(opts ...MuxOption) LoggerOption
Mux configures a backend to dispatch log messages to multiple targets.
The Mux factory accepts a slice of configuration functions.
type LogtailOption ¶ added in v0.2.0
type LogtailOption = func(*logtail) error // LogtailOption is a function that configures a logtail transport
func LogtailEndpoint ¶ added in v0.2.0
func LogtailEndpoint(s string) LogtailOption
LogtailEndpoint configures the endpoint of the BetterStack Logs service.
func LogtailMaxBatch ¶ added in v0.2.0
func LogtailMaxBatch(m int) LogtailOption
configures the maximum number of log entries to send to the BetterStack Logs service in a single request. The default value is 16.
A batch is sent to the BetterStack Logs service when the number of entries in the batch reaches this number, even if the max latency time has not been reached.
func LogtailMaxLatency ¶ added in v0.2.0
func LogtailMaxLatency(d time.Duration) LogtailOption
configures the maximum time to wait before sending a batch of log entries to the BetterStack Logs service. If the batch contains at least one entry it will be sent after this time has elapsed.
func LogtailSourceToken ¶ added in v0.2.0
func LogtailSourceToken(s string) LogtailOption
LogtailSourceToken configures the source token of the log entries sent to the BetterStack Logs service.
The parameter to this function may be:
- the name of an environment variable holding the source token value
- the name of a file containing the source token value (and ONLY the source value)
- a source token value (not recommended, to avoid leaking secrets in source)
type MockEntry ¶ added in v0.2.0
type MockEntry struct {
// contains filtered or unexported fields
}
MockEntry represents a log MockEntry. It may represent an expected MockEntry or an actual one; for an expected entry, the actual field will reference the corresponding entry that was dispatched (if any).
For an expected MockEntry, any field that has a nil expected value is deemed to match as long as that field is present in the target fields (regardless of value), otherwise the value of that field in the target must match the expected field value.
type MockLog ¶
type MockLog interface { ExpectEntry(...EntryExpectation) ExpectTrace(...EntryExpectation) ExpectDebug(...EntryExpectation) ExpectInfo(...EntryExpectation) ExpectWarn(...EntryExpectation) ExpectFatal(...EntryExpectation) ExpectationsWereMet() error Reset() }
MockLog is an interface implemented by a mock logger that can be used to verify that log entries are emitted as expected.
type MsgpackOption ¶ added in v0.2.0
type MsgpackOption func(*msgpackfmt) error // MsgpackOption is a function for configuring a msgpack formatter
func MsgpackKeys ¶ added in v0.2.0
func MsgpackKeys(keys map[FieldId]string) MsgpackOption
MsgpackKeys configures the keys used for the each of the core fields in a log entry: time, level, message, file and function.
A map[FieldId]string is used to override the default label for each field that is required; if a field is not included in the map, the default label will continue to be used for that field.
The default labels for each field are:
TimeField: time LevelField: level MessageField: message
Although the label for each field may be configured, the inclusion of these fields and their order is fixed, and cannot be changed.
func MsgpackLevels ¶ added in v0.2.0
func MsgpackLevels(levels map[Level]string) MsgpackOption
MsgpackLevels configures the values used for the Level field in msgpack formatted log entries.
type MuxOption ¶
type MuxOption = func(*mux) error
MuxOption is a configuration function for a mux backend.
func MuxTarget ¶ added in v0.2.0
func MuxTarget(cfg ...TargetOption) MuxOption
MuxTarget is a MuxOption that configures and adds a target to a mux.
type StdioTransportOption ¶ added in v0.2.0
type StdioTransportOption = func(*stdioTransport) error // StdioOption is a function for configuring a stdio transport
type TargetOption ¶
type TargetOption = func(*mux, *target) error // TargetOption is a function that configures a target
func TargetFormat ¶
func TargetFormat(f any) TargetOption
TargetFormat sets the Formatter for a target. The parameter to this function must be a Formatter or a (string) id of a Formatter previously added to the mux.
func TargetLevel ¶
func TargetLevel(level Level) TargetOption
TargetLevel sets the minimum Level of entries that will be dispatched to a target.
func TargetTransport ¶
func TargetTransport(cfg TransportFactory) TargetOption
TargetTransport sets the Transport for a target.
type TransportFactory ¶
type TransportFactory = func() (transport, error)
func StdioTransport ¶
func StdioTransport(w io.Writer) TransportFactory
Stdio returns a factory that configures a transport to log messages to an io.Writer.
Source Files
¶
- batch.go
- bytes.go
- callsite.go
- context.go
- enrichment.go
- entry.go
- errors.go
- exit.go
- fields.go
- interfaces.go
- jsonFormatter.go
- jsonFormatterOptions.go
- levelLogger.go
- levels.go
- logcontext.go
- logfmt.go
- logfmtOptions.go
- logger.go
- loggerOptions.go
- logtailBatchHandler.go
- logtailTransport.go
- logtailTransportOptions.go
- mock.go
- mockEntry.go
- mockExpectations.go
- msgpackFormatter.go
- msgpackFormatterOptions.go
- mux.go
- muxOptions.go
- noop.go
- now.go
- stdioBackend.go
- stdioTransport.go
- target.go
- targetOptions.go
- trace.go