message

package
v0.0.0-...-0df0820 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2018 License: Apache-2.0 Imports: 16 Imported by: 0

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.

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

This section is empty.

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 interface{}) error

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() error

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

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

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

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() interface{}

	// 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

	// Annotate makes it possible for Senders and Journalers to
	// add structured data to a log message. May return an error
	// when the key alrady exists.
	Annotate(string, interface{}) error

	// Priority returns the priority of the message.
	Priority() level.Priority
	SetPriority(level.Priority) error
}

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 CollectAllProcesses

func CollectAllProcesses() []Composer

CollectAllProcesses returns a slice of populated ProcessInfo message.Composer interfaces for all processes currently running on a system.

func CollectGoStats

func CollectGoStats() Composer

CollectGoStats returns some very basic runtime statistics about the current go process, using runtimeMemStats and runtime.NumGoroutine.

Internally, this uses message.Fields{}. Call this at most once a second. Values are cached between calls: if you use this function, do not call it more than once a second.

The basic idea is taken from https://github.com/YoSmudge/go-stats,.

func CollectProcessInfo

func CollectProcessInfo(pid int32) Composer

CollectProcessInfo returns a populated ProcessInfo message.Composer instance for the specified pid.

func CollectProcessInfoSelf

func CollectProcessInfoSelf() Composer

CollectProcessInfoSelf returns a populated ProcessInfo message.Composer for the pid of the current process.

func CollectProcessInfoSelfWithChildren

func CollectProcessInfoSelfWithChildren() []Composer

CollectProcessInfoSelfWithChildren returns a slice of populated ProcessInfo message.Composer instances for the current process and all children processes.

func CollectProcessInfoWithChildren

func CollectProcessInfoWithChildren(pid int32) []Composer

CollectProcessInfoWithChildren returns a slice of populated ProcessInfo message.Composer instances for the process with the specified pid and all children processes for that process.

func CollectSystemInfo

func CollectSystemInfo() Composer

CollectSystemInfo returns a populated SystemInfo object, without a message.

func ConvertToComposer

func ConvertToComposer(p level.Priority, message interface{}) Composer

ConvertToComposer can coerce unknown objects into Composer instances, as possible.

func MakeFields

func MakeFields(f Fields) Composer

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

func MakeFieldsMessage

func MakeFieldsMessage(message string, f Fields) Composer

MakeFieldsMessage constructs a fields Composer from a message string and Fields object, without specifying the priority of the message.

func MakeGroupComposer

func MakeGroupComposer(msgs ...Composer) Composer

MakeGroupComposer provides a variadic interface for creating a GroupComposer.

func MakeJiraMessage

func MakeJiraMessage(issue JiraIssue) Composer

MakeJiraMessage creates a jiraMessage instance with the given JiraIssue.

func MakeSimpleFields

func MakeSimpleFields(f Fields) Composer

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

func MakeSimpleFieldsMessage

func MakeSimpleFieldsMessage(msg string, f Fields) Composer

MakeSimpleFieldsMessage returns a structured Composer that does not attach basic logging metadata, but allows callers to specify the message (the "message" field) as a string.

func MakeSystemInfo

func MakeSystemInfo(message string) Composer

MakeSystemInfo builds a populated SystemInfo object with the specified message.

func NewBytes

func NewBytes(b []byte) Composer

NewBytes provides a basic message consisting of a single line.

func NewBytesMessage

func NewBytesMessage(p level.Priority, b []byte) Composer

NewBytesMessage provides a Composer interface around a byte slice, which are always logable unless the string is empty.

func NewDefaultMessage

func NewDefaultMessage(p level.Priority, message string) Composer

NewDefaultMessage provides a Composer interface around a single string, which are always logable unless the string is empty.

func NewError

func NewError(err error) Composer

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

func NewErrorMessage

func NewErrorMessage(p level.Priority, err error) Composer

NewErrorMessage takes an error object and returns a Composer instance that only renders a loggable message when the error is non-nil.

func NewErrorWrap

func NewErrorWrap(err error, base string, args ...interface{}) Composer

NewErrorWrap produces a message.Composer that combines the functionality of an Error composer that renders a loggable error message for non-nil errors with a normal formatted message (e.g. fmt.Sprintf). These messages only log if the error is non-nil.

func NewErrorWrapMessage

func NewErrorWrapMessage(p level.Priority, err error, base string, args ...interface{}) Composer

NewErrorWrapMessage produces a fully configured message.Composer that combines the functionality of an Error composer that renders a loggable error message for non-nil errors with a normal formatted message (e.g. fmt.Sprintf). These messages only log if the error is non-nil.

func NewErrorWrappedComposer

func NewErrorWrappedComposer(err error, m Composer) Composer

NewErrorWrappedComposer provvides a way to construct a log message that annotates an error.

func NewFields

func NewFields(p level.Priority, f Fields) Composer

NewFields constructs a full configured fields Composer.

func NewFieldsMessage

func NewFieldsMessage(p level.Priority, message string, f Fields) Composer

NewFieldsMessage creates a fully configured Composer instance that will attach some additional structured data. This constructor allows you to include a string message as well as Fields object.

func NewFormatted

func NewFormatted(base string, args ...interface{}) Composer

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

func NewFormattedMessage

func NewFormattedMessage(p level.Priority, base string, args ...interface{}) Composer

NewFormattedMessage takes arguments as fmt.Sprintf(), and returns an object that only runs the format operation as part of the String() method.

func NewGroupComposer

func NewGroupComposer(msgs []Composer) Composer

NewGroupComposer returns a GroupComposer object from a slice of Composers.

func NewJiraMessage

func NewJiraMessage(project, summary string, fields ...JiraField) Composer

NewJiraMessage creates and returns a fully formed jiraMessage, which implements message.Composer. project string and summary string are required, and any number of additional fields may be included. Fields with keys Reporter, Assignee, Type, and Labels will be specifically assigned to respective fields in the new jiraIssue included in the jiraMessage, (e.g. JiraIssue.Reporter, etc), and all other fields will be included in jiraIssue.Fields.

func NewLine

func NewLine(args ...interface{}) Composer

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

func NewLineMessage

func NewLineMessage(p level.Priority, args ...interface{}) Composer

NewLineMessage is a basic constructor for a type that, given a bunch of arguments, calls fmt.Sprintln() on the arguments passed to the constructor during the String() operation. Use in combination with Compose[*] logging methods.

func NewProcessInfo

func NewProcessInfo(priority level.Priority, pid int32, message string) Composer

NewProcessInfo constructs a fully configured and populated Processinfo message.Composer instance for the specified process.

func NewSimpleFields

func NewSimpleFields(p level.Priority, f Fields) Composer

NewSimpleFields returns a structured Composer that does not attach basic logging metadata and allows callers to configure the messages' log level.

func NewSimpleFieldsMessage

func NewSimpleFieldsMessage(p level.Priority, msg string, f Fields) Composer

NewSimpleFieldsMessage returns a structured Composer that does not attach basic logging metadata, but allows callers to specify the message (the "message" field) as well as the message's log-level.

func NewStack

func NewStack(skip int, message string) Composer

NewStack 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 NewStackFormatted

func NewStackFormatted(skip int, message string, args ...interface{}) Composer

NewStackFormatted returns a composer that builds a fmt.Printf style message that also captures a stack trace. Use the skip argument to skip frames if your embedding this in your own wrapper or wrappers.

func NewStackLines

func NewStackLines(skip int, messages ...interface{}) Composer

NewStackLines returns a composer that builds a fmt.Println style message that also captures a stack trace. Use the skip argument to skip frames if your embedding this in your own wrapper or wrappers.

func NewString

func NewString(m string) Composer

NewString provides a basic message consisting of a single line.

func NewSystemInfo

func NewSystemInfo(priority level.Priority, message string) Composer

NewSystemInfo returns a fully configured and populated SystemInfo object.

func When

func When(cond bool, m interface{}) 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 ...interface{}) 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 ...interface{}) 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 WrapError

func WrapError(err error, m interface{}) 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 ...interface{}) Composer

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

func WrapStack

func WrapStack(skip int, msg interface{}) 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 Fields

type Fields map[string]interface{}

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

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

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.

The GroupComposer type is not safe for concurrent access.

func (*GroupComposer) Annotate

func (g *GroupComposer) Annotate(k string, v interface{}) error

Annotate calls the Annotate method of every non-nil component Composer *but does not propogate

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() interface{}

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

SetPriority sets the priority of all constituent Composers *only* if the existing level is unset, and does not propogate an error, but will *not* unset the level of the compser and will return an error in this case.

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.

type JiraField

type JiraField struct {
	Key   string
	Value interface{}
}

JiraField is a struct composed of a key-value pair.

type JiraIssue

type JiraIssue struct {
	Project     string
	Summary     string
	Description string
	Reporter    string
	Assignee    string
	Type        string
	Components  []string
	Labels      []string
	// ... other fields
	Fields map[string]string
}

JiraIssue requires project and summary to create a real jira issue. Other fields depend on permissions given to the specific project, and all fields must be legitimate custom fields defined for the project. To see whether you have the right permissions to create an issue with certain fields, check your JIRA interface on the web.

type ProcessInfo

type ProcessInfo struct {
	Message        string                   `json:"message,omitempty" bson:"message,omitempty"`
	Pid            int32                    `json:"pid" bson:"pid"`
	Parent         int32                    `json:"parentPid,omitempty" bson:"parentPid,omitempty"`
	Threads        int                      `json:"numThreads,omitempty" bson:"numThreads,omitempty"`
	Command        string                   `json:"command,omitempty" bson:"command,omitempty"`
	CPU            cpu.TimesStat            `json:"cpu,omitempty" bson:"cpu,omitempty"`
	IoStat         process.IOCountersStat   `json:"io,omitempty" bson:"io,omitempty"`
	NetStat        []net.IOCountersStat     `json:"net,omitempty" bson:"net,omitempty"`
	Memory         process.MemoryInfoStat   `json:"mem,omitempty" bson:"mem,omitempty"`
	MemoryPlatform process.MemoryInfoExStat `json:"memExtra,omitempty" bson:"memExtra,omitempty"`
	Errors         []string                 `json:"errors,omitempty" bson:"errors,omitempty"`
	Base           `json:"metadata,omitempty" bson:"metadata,omitempty"`
	// contains filtered or unexported fields
}

ProcessInfo holds the data for per-process statistics (e.g. cpu, memory, io). The Process info composers produce messages in this form.

func (*ProcessInfo) Loggable

func (p *ProcessInfo) Loggable() bool

Loggable returns true when the Processinfo structure has been populated.

func (*ProcessInfo) Raw

func (p *ProcessInfo) Raw() interface{}

Raw always returns the ProcessInfo object, however it will call the Collect method of the base operation first.

func (*ProcessInfo) String

func (p *ProcessInfo) String() string

String returns a string representation of the message, lazily rendering the message, and caching it privately.

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 StackTrace

type StackTrace struct {
	Context interface{} `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

type SystemInfo

type SystemInfo struct {
	Message    string                `json:"message,omitempty" bson:"message,omitempty"`
	CPU        cpu.TimesStat         `json:"cpu,omitempty" bson:"cpu,omitempty"`
	CPUPercent float64               `json:"cpu_percent,omitempty" bson:"cpu_percent,omitempty"`
	NumCPU     int                   `json:"num_cpus,omitempty" bson:"num_cpus,omitempty"`
	VMStat     mem.VirtualMemoryStat `json:"vmstat,omitempty" bson:"vmstat,omitempty"`
	NetStat    net.IOCountersStat    `json:"netstat,omitempty" bson:"netstat,omitempty"`
	Partitions []disk.PartitionStat  `json:"partitions,omitempty" bson:"partitions,omitempty"`
	Usage      []disk.UsageStat      `json:"usage,omitempty" bson:"usage,omitempty"`
	IOStat     []disk.IOCountersStat `json:"iostat,omitempty" bson:"iostat,omitempty"`
	Errors     []string              `json:"errors,omitempty" bson:"errors,omitempty"`
	Base       `json:"metadata,omitempty" bson:"metadata,omitempty"`
	// contains filtered or unexported fields
}

SystemInfo is a type that implements message.Composer but also collects system-wide resource utilization statistics about memory, CPU, and network use, along with an optional message.

func (*SystemInfo) Loggable

func (s *SystemInfo) Loggable() bool

Loggable returns true when the Processinfo structure has been populated.

func (*SystemInfo) Raw

func (s *SystemInfo) Raw() interface{}

Raw always returns the SystemInfo object, however it will call the Collect method of the base operation first.

func (*SystemInfo) String

func (s *SystemInfo) String() string

String returns a string representation of the message, lazily rendering the message, and caching it privately.

Jump to

Keyboard shortcuts

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