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
- func GetDefaultFieldsMessage(msg Composer, val string) string
- type Base
- type Builder
- func (b *Builder) Annotate(key string, val any) *Builder
- func (b *Builder) Any(msg any) *Builder
- func (b *Builder) AnyMap(f map[string]any) *Builder
- func (b *Builder) Bytes(in []byte) *Builder
- func (b *Builder) Composer(c Composer) *Builder
- func (b *Builder) ComposerProducer(f ComposerProducer) *Builder
- func (b *Builder) CovertProducer(f func() any) *Builder
- func (b *Builder) Error(err error) *Builder
- func (b *Builder) ErrorProducer(f ErrorProducer) *Builder
- func (b *Builder) F(tmpl string, a ...any) *Builder
- func (b *Builder) Fields(f Fields) *Builder
- func (b *Builder) FieldsProducer(f func() Fields) *Builder
- func (b *Builder) Group() *Builder
- func (b *Builder) KV(kvs ...KV) *Builder
- func (b *Builder) KVProducer(f KVProducer) *Builder
- func (b *Builder) KVs(kvs KVs) *Builder
- func (b *Builder) Level(l level.Priority) *Builder
- func (b *Builder) Ln(args ...any) *Builder
- func (b *Builder) Message() Composer
- func (b *Builder) Send()
- func (b *Builder) SetGroup(sendAsGroup bool) *Builder
- func (b *Builder) String(str string) *Builder
- func (b *Builder) StringMap(f map[string]string) *Builder
- func (b *Builder) Strings(ss []string) *Builder
- func (b *Builder) Ungroup() *Builder
- func (b *Builder) When(cond bool) *Builder
- type Composer
- func Convert[T any](input T) Composer
- func MakeBytes(b []byte) Composer
- func MakeError(err error) Composer
- func MakeFields(f Fields) Composer
- func MakeFormat(base string, args ...any) Composer
- func MakeKV(kvs ...KV) Composer
- func MakeKVs(kvs KVs) Composer
- func MakeLines(args ...any) Composer
- func MakeProducer[T any, F ~func() T](fp F) Composer
- func MakeSimpleBytes(b []byte) Composer
- func MakeSimpleFields(f Fields) Composer
- func MakeSimpleKV(kvs ...KV) Composer
- func MakeSimpleKVs(kvs KVs) Composer
- func MakeSimpleString(m string) Composer
- func MakeStack(skip int, message string) Composer
- func MakeString(m string) Composer
- func Unwind(comp Composer) []Composer
- func When(cond bool, m any) Composer
- func WhenMsg(cond bool, m string) Composer
- func Whenf(cond bool, m string, args ...any) Composer
- func Whenln(cond bool, args ...any) Composer
- func Wrap(parent Composer, msg any) Composer
- func WrapError(err error, m any) Composer
- func WrapErrorf(err error, msg string, args ...any) Composer
- func WrapStack(skip int, msg any) Composer
- type ComposerProducer
- type ErrorProducer
- type Fields
- type FieldsProducer
- type GroupComposer
- func (g *GroupComposer) Add(msg Composer)
- func (g *GroupComposer) Annotate(k string, v any)
- func (g *GroupComposer) Append(msgs ...Composer)
- func (g *GroupComposer) Extend(msg []Composer)
- func (g *GroupComposer) Loggable() bool
- func (g *GroupComposer) Messages() []Composer
- func (g *GroupComposer) Priority() level.Priority
- func (g *GroupComposer) Raw() any
- func (g *GroupComposer) SetPriority(l level.Priority)
- func (g *GroupComposer) String() string
- func (g *GroupComposer) Structured() bool
- func (g *GroupComposer) Unwrap() Composer
- type KV
- type KVProducer
- type KVs
- type Marshaler
- type StackFrame
- type StackFrames
- type StackTrace
Constants ¶
const FieldsMsgName = "message"
FieldsMsgName is the name of the default "message" field in the fields structure.
Variables ¶
This section is empty.
Functions ¶
func GetDefaultFieldsMessage ¶
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 ¶
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 ¶
IsZero returns true when Base is nil or it is non-nil and none of its fields are set.
func (*Base) SetPriority ¶
SetPriority allows you to configure the priority of the message. Returns an error if the priority is not valid.
func (*Base) Structured ¶
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 NewBuilder ¶
NewBuilder constructs the chainable builder type, and initializes the error tracking and establishes a connection to the sender.
func (*Builder) Annotate ¶
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) ComposerProducer ¶
func (b *Builder) ComposerProducer(f ComposerProducer) *Builder
func (*Builder) CovertProducer ¶ added in v0.2.1
func (*Builder) ErrorProducer ¶
func (b *Builder) ErrorProducer(f ErrorProducer) *Builder
func (*Builder) Fields ¶
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 (*Builder) KVProducer ¶ added in v0.1.1
func (b *Builder) KVProducer(f KVProducer) *Builder
func (*Builder) KVs ¶ added in v0.1.1
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 ¶
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) Message ¶
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.
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 MakeError ¶
MakeError returns an error composer, like NewErrorMessage, but without the requirement to specify priority, which you may wish to specify directly.
func MakeFields ¶
MakeFields creates a composer interface from *just* a Fields instance.
func MakeFormat ¶
MakeFormat returns a message.Composer roughly equivalent to an fmt.Sprintf().
func MakeProducer ¶
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 ¶
MakeSimpleBytes produces a bytes-wrapping message but does not collect metadata.
func MakeSimpleFields ¶
MakeSimpleFields returns a structured Composer that does not attach basic logging metadata.
func MakeSimpleKV ¶ added in v0.1.1
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
MakeSimpleKVs constructs a composer using KV pairs that does *not* populate the "base" structure (with time, hostname and pid information).
func MakeSimpleString ¶
MakeSimpleString produces a string message that does not attach process metadata.
func MakeStack ¶
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 ¶
MakeString provides a basic message consisting of a single line.
func Unwind ¶ added in v0.2.1
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WrapErrorf wraps an error and creates a composer using a Sprintf-style formated composer.
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 ¶
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
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
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) UnmarshalJSON ¶ added in v0.1.1
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