message

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: May 9, 2023 License: Apache-2.0 Imports: 13 Imported by: 38

Documentation

Overview

package message defines the Composer interface and a handful of implementations which represent the structure for messages produced by grip.

Message Composers

The Composer interface provides a common way to define messages, with two main goals:

1. Provide a common interface for representing structured and unstructured logging data regardless of logging backend or interface.

2. Provide a method for *lazy* construction of log messages so they're built *only* if a log message is over threshold.

The message package also contains many implementations of Composer which should support most logging use cases. However, any package using grip for logging may need to implement custom composer types.

The Composer implementations in the message package compose the Base type to provide some common functionality around priority setting and data collection.

The logging methods in the Journaler interface typically convert all inputs into a reasonable Composer implementations.

Error Messages

The error message composers underpin the Catch<> logging messages, which allow you to log error messages but let the logging system elide logging for nil errors.

Functional Messages

Grip can automatically convert three types of functions into messages:

func() Fields
func() Composer
func() error

The benefit of these functions is that they're only called if the message is above the logging threshold. In the case of conditional logging (i.e. When), if the conditional is false, then the function is never called.

in the case of all the buffered sending implementation, the function call can be deferred and run outside of the main thread, and so may be an easy way to defer message production outside in cases where messages may be complicated.

Additionally, the message conversion in grip's logging method can take these function types and convert them to these messages, which can clean up some call-site operations, and makes it possible to use defer with io.Closer methods without wrapping the method in an additional function, as in:

defer grip.Error(file.Close)

Although the WrapErrorFunc method, as in the following may permit useful annotation, as follows, which has the same "lazy" semantics.

defer grip.Error(message.WrapErrorFunc(file.Close, message.Fields{}))

Bytes Messages

The bytes types make it possible to send a byte slice as a message.

Stack Messages

The Stack message Composer implementations capture a full stacktrace information during message construction, and attach a message to that trace. The string form of the message includes the package and file name and line number of the last call site, while the Raw form of the message includes the entire stack. Use with an appropriate sender to capture the desired output.

All stack message constructors take a "skip" parameter which tells how many stack frames to skip relative to the invocation of the constructor. Skip values less than or equal to 0 become 1, and are equal the call site of the constructor, use larger numbers if you're wrapping these constructors in our own infrastructure.

In general Composers are lazy, and defer work until the message is being sent; however, the stack Composers must capture the stack when they're called rather than when they're sent to produce meaningful data.

Index

Constants

View Source
const FieldsMsgName = "message"

FieldsMsgName is the name of the default "message" field in the fields structure.

Variables

This section is empty.

Functions

func GetDefaultFieldsMessage

func GetDefaultFieldsMessage(msg Composer, val string) string

GetDefaultFieldsMessage returns a "short" message form, to avoid needing to call .String() on the type, which produces a string form of the message. If the message has a short form (either in the map, or separate), it's returned, otherwise the "val" is returned.

For composers not that don't wrap Fields, this function will always return the input value.

Types

type Base

type Base struct {
	Level    level.Priority `bson:"level,omitempty" json:"level,omitempty" yaml:"level,omitempty"`
	Hostname string         `bson:"hostname,omitempty" json:"hostname,omitempty" yaml:"hostname,omitempty"`
	Time     time.Time      `bson:"time,omitempty" json:"time,omitempty" yaml:"time,omitempty"`
	Process  string         `bson:"process,omitempty" json:"process,omitempty" yaml:"process,omitempty"`
	Pid      int            `bson:"pid,omitempty" json:"pid,omitempty" yaml:"pid,omitempty"`
	Context  Fields         `bson:"context,omitempty" json:"context,omitempty" yaml:"context,omitempty"`
}

Base provides a simple embedable implementation of some common aspects of a message.Composer. Additionally the Collect() method collects some simple metadata, that may be useful for some more structured logging applications.

func (*Base) Annotate

func (b *Base) Annotate(key string, value any)

Annotate makes it possible for callers and senders to add structured data to a message. This may be overridden for some implementations.

func (*Base) Collect

func (b *Base) Collect()

Collect records the time, process name, and hostname. Useful in the context of a Raw() method.

func (*Base) IsZero

func (b *Base) IsZero() bool

IsZero returns true when Base is nil or it is non-nil and none of its fields are set.

func (*Base) Priority

func (b *Base) Priority() level.Priority

Priority returns the configured priority of the message.

func (*Base) SetPriority

func (b *Base) SetPriority(l level.Priority)

SetPriority allows you to configure the priority of the message. Returns an error if the priority is not valid.

func (*Base) Structured

func (b *Base) Structured() bool

Structured returns true if there are any annotations. Otherwise false. Most Composer implementations should override.

type Builder

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

Builder provides a chainable message building interface.

Builders can produce multiple messages. If the SetGroup value is true (also controlled via the Group/Ungroup methods,) then the Send operation is called once for the group of messages, and otherwise the send operation is called once for every constituent message (which is the default.)

Callers must call Send() at the end of the builder chain to send the message.

func AddProducerToBuilder added in v0.2.1

func AddProducerToBuilder[T any, F ~func() T](b *Builder, fn F) *Builder

func NewBuilder

func NewBuilder(send func(Composer)) *Builder

NewBuilder constructs the chainable builder type, and initializes the error tracking and establishes a connection to the sender.

func (*Builder) Annotate

func (b *Builder) Annotate(key string, val any) *Builder

Annotate adds key-value pairs to the composer. Most message types add this to the underlying structured data that's part of messages payloads, and Fields-based messages handle append these annotations directly to the main body of their message. Some sender/message formating handlers and message types may not render annotations in all cases.

func (*Builder) Any

func (b *Builder) Any(msg any) *Builder

func (*Builder) AnyMap

func (b *Builder) AnyMap(f map[string]any) *Builder

func (*Builder) Bytes

func (b *Builder) Bytes(in []byte) *Builder

func (*Builder) Composer

func (b *Builder) Composer(c Composer) *Builder

func (*Builder) ComposerProducer

func (b *Builder) ComposerProducer(f ComposerProducer) *Builder

func (*Builder) CovertProducer added in v0.2.1

func (b *Builder) CovertProducer(f func() any) *Builder

func (*Builder) Error

func (b *Builder) Error(err error) *Builder

func (*Builder) ErrorProducer

func (b *Builder) ErrorProducer(f ErrorProducer) *Builder

func (*Builder) F

func (b *Builder) F(tmpl string, a ...any) *Builder

func (*Builder) Fields

func (b *Builder) Fields(f Fields) *Builder

Fields, creates a new fields message if no message has been defined, and otherwise annotates the existing message with the content of the input map. This is the same semantics as StringMap and AnyMap methods

func (*Builder) FieldsProducer

func (b *Builder) FieldsProducer(f func() Fields) *Builder

func (*Builder) Group

func (b *Builder) Group() *Builder

func (*Builder) KV added in v0.1.1

func (b *Builder) KV(kvs ...KV) *Builder

func (*Builder) KVProducer added in v0.1.1

func (b *Builder) KVProducer(f KVProducer) *Builder

func (*Builder) KVs added in v0.1.1

func (b *Builder) KVs(kvs KVs) *Builder

KVs, creates a new key-value message if no message has been defined, and otherwise annotates the existing message with the content of the input set. This is the same semantics as the Fields message.

func (*Builder) Level

func (b *Builder) Level(l level.Priority) *Builder

Level sets the priority of the message. Call this after creating a message via another method, otherwise an error is generated and added to the builder. Additionally an error is added to the builder if the level is not valid.

func (*Builder) Ln

func (b *Builder) Ln(args ...any) *Builder

func (*Builder) Message

func (b *Builder) Message() Composer

Message resolves the message built by the builder, flattening (if needed,) multiple messages into a single grouped message, and wrapping the message with an error if any were produced while building the message.

If no message is built and no errors are registered, then Message resolves a non-loggable error message.

If multiple messages are added to the logger they are stored in a wrapped form, so that modifications to the message (annotations, levels, etc.) affect the most recent message, and then later converted to a group.

func (*Builder) Send

func (b *Builder) Send()

Send finalizes the chain and delivers the message. Send resolves the built message using the Message method.

If there are multiple messages captured in the builder, and the Group() is set to true, then the GroupComposer's default behavior is used, otherwise, each message is sent individually.

func (*Builder) SetGroup

func (b *Builder) SetGroup(sendAsGroup bool) *Builder

func (*Builder) String

func (b *Builder) String(str string) *Builder

func (*Builder) StringMap

func (b *Builder) StringMap(f map[string]string) *Builder

func (*Builder) Strings

func (b *Builder) Strings(ss []string) *Builder

func (*Builder) Ungroup

func (b *Builder) Ungroup() *Builder

func (*Builder) When

func (b *Builder) When(cond bool) *Builder

When makes the message conditional. Pass a statement to this function, that when false will cause the rest of the message to be non-loggable. This may combine well with message types that are expensive to calculate, or the Fields/Composer/Error producer methods.

type Composer

type Composer interface {
	// Returns the content of the message as a string for use in
	// line-printing logging engines.
	String() string

	// A "raw" format of the logging output for use by some Sender
	// implementations that write logged items to interfaces that
	// accept JSON or another structured format.
	Raw() any

	// Returns "true" when the message has content and should be
	// logged, and false otherwise. When false, the sender can
	// (and should!) ignore messages even if they are otherwise
	// above the logging threshold.
	Loggable() bool

	// Returns "true" when the underlying message type has
	// substantial structured data and should be handled by the
	// sender as structured data.
	Structured() bool

	// Annotate makes it possible for users (including internally)
	// to add structured data to a log message. Implementations may
	// choose to override key/value pairs that already exist.
	Annotate(string, any)

	// Priority returns the priority of the message.
	Priority() level.Priority

	// SetPriority sets the messaages' log level. The high level
	// logging interfaces set this before sending the
	// message. If you send a message to a sender directly without
	// setting the level, or set the level to an invalid level,
	// the message is not loggable.
	SetPriority(level.Priority)
}

Composer defines an interface with a "String()" method that returns the message in string format. Objects that implement this interface, in combination to the Compose[*] operations, the String() method is only caled if the priority of the method is greater than the threshold priority. This makes it possible to defer building log messages (that may be somewhat expensive to generate) until it's certain that we're going to be outputting the message.

func Convert

func Convert[T any](input T) Composer

Convert produces a composer interface for arbitrary input.

func MakeBytes

func MakeBytes(b []byte) Composer

MakeBytes provides a basic message consisting of a single line.

func MakeError

func MakeError(err error) Composer

MakeError returns an error composer, like NewErrorMessage, but without the requirement to specify priority, which you may wish to specify directly.

func MakeFields

func MakeFields(f Fields) Composer

MakeFields creates a composer interface from *just* a Fields instance.

func MakeFormat

func MakeFormat(base string, args ...any) Composer

MakeFormat returns a message.Composer roughly equivalent to an fmt.Sprintf().

func MakeKV added in v0.1.1

func MakeKV(kvs ...KV) Composer

MakeKV constructs a new Composer using KV pairs.

func MakeKVs added in v0.1.1

func MakeKVs(kvs KVs) Composer

MakeKVs constructs a new Composer using KV pairs.

func MakeLines

func MakeLines(args ...any) Composer

MakeLines returns a message Composer roughly equivalent to fmt.Sprintln().

func MakeProducer

func MakeProducer[T any, F ~func() T](fp F) Composer

MakeProduer constructs a lazy Producer message composer.

Producer functions are only called before calling the Loggable, String, Raw, or Annotate methods. Changing the priority does not call the function. In practice, if the priority of the message is below the logging threshold, then the function will never be called.

func MakeSimpleBytes

func MakeSimpleBytes(b []byte) Composer

MakeSimpleBytes produces a bytes-wrapping message but does not collect metadata.

func MakeSimpleFields

func MakeSimpleFields(f Fields) Composer

MakeSimpleFields returns a structured Composer that does not attach basic logging metadata.

func MakeSimpleKV added in v0.1.1

func MakeSimpleKV(kvs ...KV) Composer

MakeSimpleKV constructs a composer using KV pairs that does *not* populate the "base" structure (with time, hostname and pid information).

func MakeSimpleKVs added in v0.1.1

func MakeSimpleKVs(kvs KVs) Composer

MakeSimpleKVs constructs a composer using KV pairs that does *not* populate the "base" structure (with time, hostname and pid information).

func MakeSimpleString

func MakeSimpleString(m string) Composer

MakeSimpleString produces a string message that does not attach process metadata.

func MakeStack

func MakeStack(skip int, message string) Composer

MakeStack builds a Composer implementation that captures the current stack trace with a single string message. Use the skip argument to skip frames if your embedding this in your own wrapper or wrappers.

func MakeString

func MakeString(m string) Composer

MakeString provides a basic message consisting of a single line.

func Unwind added in v0.2.1

func Unwind(comp Composer) []Composer

Unwind takes a composer and, if it has been wrapped, unwraps it and produces a group composer of all the constituent messages. If there are group messages in the stack, they are added (flattened) in the new output group.

func When

func When(cond bool, m any) Composer

When returns a conditional message that is only logged if the condition is bool. Converts the second argument to a composer, if needed, using the same rules that the logging methods use.

func WhenMsg

func WhenMsg(cond bool, m string) Composer

WhenMsg returns a conditional message that is only logged if the condition is bool, and creates a string message that will only log when the message content is not the empty string. Use this for a more strongly-typed conditional logging message.

func Whenf

func Whenf(cond bool, m string, args ...any) Composer

Whenf returns a conditional message that is only logged if the condition is bool, and creates a sprintf-style message, which will itself only log if the base expression is not the empty string.

func Whenln

func Whenln(cond bool, args ...any) Composer

Whenln returns a conditional message that is only logged if the condition is bool, and creates a sprintf-style message, which will itself only log if the base expression is not the empty string.

func Wrap

func Wrap(parent Composer, msg any) Composer

Wrap creates a new composer, converting the message to the appropriate Composer type, using the Convert() function, while preserving the parent composer. The Unwrap() function unwinds a stack of composers, flattening it into a single group composer.

func WrapError

func WrapError(err error, m any) Composer

WrapError wraps an error and creates a composer converting the argument into a composer in the same manner as the front end logging methods.

func WrapErrorf

func WrapErrorf(err error, msg string, args ...any) Composer

WrapErrorf wraps an error and creates a composer using a Sprintf-style formated composer.

func WrapStack

func WrapStack(skip int, msg any) Composer

WrapStack annotates a message, converted to a composer using the normal rules if needed, with a stack trace. Use the skip argument to skip frames if your embedding this in your own wrapper or wrappers.

type ComposerProducer

type ComposerProducer func() Composer

ComposerProducer constructs a lazy composer, and makes it easy to implement new Composers as functions returning an existing composer type. Consider the following:

grip.Info(func() message.Composer { return WrapError(validateRequest(req), message.Fields{"op": "name"})})

Grip can automatically convert these functions when passed to a logging function.

If the Fields object is nil or empty then no message is ever logged.

type ErrorProducer

type ErrorProducer func() error

ErrorProducer is a function that returns an error, and is used for constructing message that lazily wraps the resulting function which is called when the message is dispatched.

If you pass one of these functions to a logging method, the ConvertToComposer operation will construct a lazy Composer based on this function, as in:

grip.Error(func() error { return errors.New("error message") })

It may be useful also to pass a "closer" function in this form, as in:

grip.Error(file.Close)

As a special case the WrapErrorFunc method has the same semantics as other ErrorProducer methods, but makes it possible to annotate an error.

type Fields

type Fields map[string]any

Fields is a convince type that wraps map[string]any and is used for attaching structured metadata to a build request. For example:

message.Fields{"key0", <value>, "key1", <value>}

func FieldsFromMap added in v0.2.0

func FieldsFromMap[V any](in map[string]V) Fields

type FieldsProducer

type FieldsProducer func() Fields

FieldsProducer is a function that returns a structured message body as a way of writing simple Composer implementations in the form anonymous functions, as in:

grip.Info(func() message.Fields {return message.Fields{"message": "hello world!"}})

Grip can automatically convert these functions when passed to a logging function.

If the Fields object is nil or empty then no message is logged.

type GroupComposer

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

GroupComposer handles groups of composers as a single message, joining messages with a new line for the string format and returning a slice of interfaces for the Raw() form.

Unlike most composer types, the GroupComposer is exported, and provides the additional Messages() method to access the composer objects as a slice.

func BuildGroupComposer

func BuildGroupComposer(msgs ...Composer) *GroupComposer

BuildGroupComposer provides a variadic interface for creating a GroupComposer.

func MakeGroupComposer

func MakeGroupComposer(msgs []Composer) *GroupComposer

MakeGroupComposer returns a GroupComposer object from a slice of Composers.

func (*GroupComposer) Add

func (g *GroupComposer) Add(msg Composer)

Add supports adding messages to an existing group composer.

func (*GroupComposer) Annotate

func (g *GroupComposer) Annotate(k string, v any)

Annotate calls the Annotate method of every non-nil component Composer.

func (*GroupComposer) Append

func (g *GroupComposer) Append(msgs ...Composer)

Append provides a variadic alternative to the Extend method.

func (*GroupComposer) Extend

func (g *GroupComposer) Extend(msg []Composer)

Extend makes it possible to add a group of messages to an existing group composer.

func (*GroupComposer) Loggable

func (g *GroupComposer) Loggable() bool

Loggable returns true if at least one of the constituent Composers is loggable.

func (*GroupComposer) Messages

func (g *GroupComposer) Messages() []Composer

Messages returns a the underlying collection of messages.

func (*GroupComposer) Priority

func (g *GroupComposer) Priority() level.Priority

Priority returns the highest priority of the constituent Composers.

func (*GroupComposer) Raw

func (g *GroupComposer) Raw() any

Raw returns a slice of interfaces containing the raw form of all the constituent composers.

func (*GroupComposer) SetPriority

func (g *GroupComposer) SetPriority(l level.Priority)

SetPriority sets the priority of all constituent Composers *only* if the existing level is unset (or otherwise invalid), and will *not* unset the level of a constituent composer.

func (*GroupComposer) String

func (g *GroupComposer) String() string

String satisfies the fmt.Stringer interface, and returns a string of the string form of all constituent composers joined with a newline.

func (*GroupComposer) Structured

func (g *GroupComposer) Structured() bool

func (*GroupComposer) Unwrap added in v0.2.9

func (g *GroupComposer) Unwrap() Composer

type KV added in v0.1.1

type KV struct {
	Key   string
	Value any
}

KV represents an arbitrary key value pair for use in structured logging. Like the Fields type, but without the map type and it's restrictions (e.g. unique keys, random ordering in iteration,) and allows some Sender implementations to implement fast-path processing of these messages.

type KVProducer added in v0.1.1

type KVProducer func() KVs

KVProducer allows callers to delay generation of KV lists (as structured log payloads) until the log message needs to be sent (e.g. the .String() or .Raw() methods are called on the Composer interface.) While all implementations of composer provide this ability to do lazy evaluation of log messages, you can use this and other producer types to implement logging as functions rather than as implementations the Composer interface itself.

type KVs added in v0.1.1

type KVs []KV

KVs represents a collection of KV pairs, and is convertable to a Fields implementation, (e.g. a map). It implements MarshalJSON and UnmarshalJSON, via the map conversion.

func (KVs) MarshalJSON added in v0.1.1

func (kvs KVs) MarshalJSON() ([]byte, error)

func (KVs) ToFields added in v0.1.1

func (kvs KVs) ToFields() Fields

func (*KVs) UnmarshalJSON added in v0.1.1

func (kvs *KVs) UnmarshalJSON(in []byte) error

type Marshaler added in v0.2.5

type Marshaler interface {
	MarshalComposer() Composer
}

Marshaler allows arbitrary types to control how they're converted (in the default converter) to a message.Composer, without requiring that the arbitrary type itself implement Composer, for a related level of functionality.

type StackFrame

type StackFrame struct {
	Function string `bson:"function" json:"function" yaml:"function"`
	File     string `bson:"file" json:"file" yaml:"file"`
	Line     int    `bson:"line" json:"line" yaml:"line"`
}

StackFrame captures a single item in a stack trace, and is used internally and in the StackTrace output.

func (StackFrame) String

func (f StackFrame) String() string

type StackFrames

type StackFrames []StackFrame

StackFrames makes slices of stack traces printable.

func (StackFrames) String

func (f StackFrames) String() string

type StackTrace

type StackTrace struct {
	Context any         `bson:"context,omitempty" json:"context,omitempty" yaml:"context,omitempty"`
	Frames  StackFrames `bson:"frames" json:"frames" yaml:"frames"`
}

StackTrace structs are returned by the Raw method of the stackMessage type

func (StackTrace) String

func (s StackTrace) String() string

Jump to

Keyboard shortcuts

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