maleo

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2023 License: Apache-2.0 Imports: 15 Imported by: 3

README

maleo

Golang library framework to handle errors, logging, and notification in one spot

Documentation can be read from here

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNil = errors.New("<nil>")
View Source
var Option option
View Source
var Query query

Query is a namespace group that holds the maleo's Query functions.

Methods and functions under Query are utilities to search values in the error stack.

Functions

func ContextWithMaleo added in v0.4.0

func ContextWithMaleo(parent context.Context, m *Maleo) context.Context

ContextWithMaleo creates a new context with Maleo instance attached.

If there's an existing Maleo instance attached, it will be overwritten.

func DetachedContext

func DetachedContext(ctx context.Context) context.Context

DetachedContext creates a context whose lifetime is detached from the input, but the values of the context is still reachable.

DetachedContext is used by Maleo to send context.Context to Messengers that are not tied to the input lifetime.

func NewTestingMaleo

func NewTestingMaleo() (*Maleo, *TestingJSONLogger)

NewTestingMaleo returns a new Maleo instance with a TestingJSONLogger.

func NewTestingMaleoWithService

func NewTestingMaleoWithService(service Service) (*Maleo, *TestingJSONLogger)

NewTestingMaleoWithService returns a new Maleo instance with a TestingJSONLogger with a custom service metadata.

func SetGlobal

func SetGlobal(m *Maleo)

SetGlobal sets the global Maleo instance.

Maleo instance will be set to receive overrides to use Maleo instances attached to context.

func Wait added in v0.2.0

func Wait(ctx context.Context) error

Wait waits for ongoing messages for Messenger to finish.

Types

type Caller

type Caller interface {
	// Function returns the function information.
	Function() *runtime.Func
	// Name returns the function name of the caller.
	Name() string
	// ShortName returns only function name of the caller.
	ShortName() string
	// ShortSource returns only the latest three items path in the File Path where the Caller comes from.
	ShortSource() string
	// String Sets this caller as `file_path:line` format.
	String() string
	// Line returns the line number of the caller.
	Line() int
	// File returns the file path of the caller.
	File() string
	// PC returns the program counter of the caller.
	PC() uintptr
	// FormatAsKey Like .String(), but the returned string is usually safe for URL.
	//
	// Default implementation changes runes other than letters, digits, `-` and `.` to `_`.
	FormatAsKey() string
	// Depth returns the depth of the caller that is initially used.
	Depth() int
}

func GetCaller

func GetCaller(depth int) Caller

GetCaller returns the caller information for who calls this function. A value of 1 will return this GetCaller location. So you may want the value to be 2 or higher if you wrap this call in another function.

Returns zero value if the caller information cannot be obtained.

type CallerHint

type CallerHint interface {
	// Caller returns the caller of this type.
	Caller() Caller
}

type CodeBlockJSONMarshaler

type CodeBlockJSONMarshaler interface {
	CodeBlockJSON() ([]byte, error)
}

type CodeHint

type CodeHint interface {
	// Code Gets the original code of the type.
	Code() int
}

type ContextHint

type ContextHint interface {
	// Context returns the context of this type.
	Context() []any
}

type Display

type Display interface {
	// Display returns a human-readable and rich with information for the implementer.
	Display() string
}

type DisplayWriter

type DisplayWriter interface {
	// WriteDisplay Writes the Display() string to the writer instead of being allocated as value.
	WriteDisplay(w LineWriter)
}

type EngineOption

type EngineOption interface {
	// contains filtered or unexported methods
}

type EngineOptionBuilder

type EngineOptionBuilder []EngineOption

func (EngineOptionBuilder) EntryConstructor

EntryConstructor sets the entry constructor for the engine.

func (EngineOptionBuilder) EntryMessageContextConstructor

func (e EngineOptionBuilder) EntryMessageContextConstructor(mc EntryMessageContextConstructor) EngineOptionBuilder

EntryMessageContextConstructor sets the message context constructor for the engine.

func (EngineOptionBuilder) ErrorConstructor

ErrorConstructor sets the error constructor for the engine.

func (EngineOptionBuilder) ErrorMessageContextConstructor

func (e EngineOptionBuilder) ErrorMessageContextConstructor(mc ErrorMessageContextConstructor) EngineOptionBuilder

type EngineOptionFunc

type EngineOptionFunc func(*engine)

type Entry

type Entry interface {
	CallerHint
	CodeHint
	ContextHint
	HTTPCodeHint
	KeyHint
	LevelHint
	MessageHint
	ServiceHint
	TimeHint

	/*
		Logs this entry.
	*/
	Log(ctx context.Context) Entry
	/*
		Notifies this entry to Messengers.
	*/
	Notify(ctx context.Context, opts ...MessageOption) Entry
}

type EntryBuilder

type EntryBuilder interface {
	// Code Sets the code for this entry.
	Code(i int) EntryBuilder

	// Message Sets the message for this entry.
	//
	// In built in implementation, If args are supplied, fmt.Sprintf will be called with s as base string.
	//
	// Very unlikely you will need to set this, because maleo already create the message field for you when you call maleo.NewEntry.
	Message(s string, args ...any) EntryBuilder

	// Context Sets additional data that will enrich how the entry will look.
	//
	// `maleo.Fields` is a type that is more integrated with built-in Messengers.
	// Using this type as Context value will often have special treatments for it.
	//
	// In built-in implementation, additional call to .Context() will make additional index, not replacing what you already set.
	//
	// Example:
	//
	// 	maleo.NewEntry(msg).Code(200).Context(maleo.F{"foo": "bar"}).Freeze()
	Context(ctx ...any) EntryBuilder

	// Key Sets the key for this entry. This is how Messenger will use to identify if an entry is the same as previous or not.
	//
	// In maleo's built-in implementation, by default, no key is set when creating new entry.
	//
	// Usually by not setting the key, The Messenger will generate their own key for this message.
	//
	// In built in implementation, If args are supplied, fmt.Sprintf will be called with key as base string.
	Key(key string, args ...any) EntryBuilder

	// Caller Sets the caller for this entry.
	//
	// In maleo's built-in implementation, by default, the caller is the location where you call `maleo.NewEntry`.
	Caller(c Caller) EntryBuilder

	// Time Sets the time for this entry. By default, it's already set when you call maleo.NewEntry.
	Time(time.Time) EntryBuilder

	// Level Sets the level for this entry.
	//
	// In maleo's built-in implementation, this defaults to what method you call to generate this entry.
	Level(lvl Level) EntryBuilder

	// Freeze this entry. Preventing further mutations.
	Freeze() Entry

	// Log this entry. Implicitly calling .Freeze() method.
	Log(ctx context.Context) Entry

	// Notify Sends this Entry to Messengers. Implicitly calling .Freeze() method.
	Notify(ctx context.Context, opts ...MessageOption) Entry
}

EntryBuilder is the builder for Entry.

func NewEntry added in v0.2.0

func NewEntry(msg string, args ...any) EntryBuilder

type EntryConstructor

type EntryConstructor interface {
	ConstructEntry(*EntryConstructorContext) EntryBuilder
}

type EntryConstructorContext

type EntryConstructorContext struct {
	Caller  Caller
	Message string
	Maleo   *Maleo
}

type EntryConstructorFunc

type EntryConstructorFunc func(*EntryConstructorContext) EntryBuilder

func (EntryConstructorFunc) ConstructEntry

type EntryMessageContextConstructor

type EntryMessageContextConstructor interface {
	BuildEntryMessageContext(entry Entry, param *MessageParameters) MessageContext
}

type EntryNode

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

EntryNode is the default implementation of Entry for Maleo.

func (EntryNode) Caller

func (e EntryNode) Caller() Caller

Caller returns the maleo.Caller of the entry.

func (EntryNode) Code

func (e EntryNode) Code() int

Code returns the original code of the type.

func (EntryNode) Context

func (e EntryNode) Context() []any

Context returns the context of the entry.

func (EntryNode) HTTPCode

func (e EntryNode) HTTPCode() int

HTTPCode return HTTP Status Code for the type.

func (EntryNode) Key

func (e EntryNode) Key() string

Key returns the key of the entry.

func (EntryNode) Level

func (e EntryNode) Level() Level

Level Gets the level of this message.

func (EntryNode) Log

func (e EntryNode) Log(ctx context.Context) Entry

Log logs the entry.

func (EntryNode) MarshalJSON

func (e EntryNode) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (EntryNode) Message

func (e EntryNode) Message() string

Message returns the message.

func (EntryNode) Notify

func (e EntryNode) Notify(ctx context.Context, opts ...MessageOption) Entry

Notify sends the entry to the messengers.

func (EntryNode) Service

func (e EntryNode) Service() Service

Service returns the service name of the entry.

func (EntryNode) Time

func (e EntryNode) Time() time.Time

Time returns the time of the entry.

type Error

type Error interface {
	error
	CallerHint
	CodeHint
	ContextHint
	UnwrapError
	HTTPCodeHint
	KeyHint
	ErrorWriter
	LevelHint
	MessageHint
	TimeHint
	ServiceHint

	// Log this error.
	Log(ctx context.Context) Error
	// Notify notifies this error to Messengers.
	Notify(ctx context.Context, opts ...MessageOption) Error
}

Error is an interface providing read only values to the error, and because it's read only, this is safe for multithreaded use.

func BailFreeze

func BailFreeze(msg string, args ...any) Error

BailFreeze creates new immutable Error from simple messages.

It's a shorthand for `maleo.Bail(msg, args...).Freeze()`.

NOTE: When you call .Log(ctx) or .Notify(ctx) and context is attached with a Maleo instance, the error will be logged or notified using that Maleo instance, instead of the global Maleo instance.

func WrapFreeze

func WrapFreeze(err error, msgAndArgs ...any) Error

WrapFreeze is a Shorthand for `maleo.Wrap(err).Message(message, args...).Freeze()`

Useful when just wanting to add extra simple messages to the error chain.

NOTE: When you call .Log(ctx) or .Notify(ctx) and context is attached with a Maleo instance, the error will be logged or notified using that Maleo instance, instead of the global Maleo instance.

type ErrorBuilder

type ErrorBuilder interface {
	// Code Sets the error code for this error.
	// This is used to identify the error type and how maleohttp will interact with this error.
	Code(i int) ErrorBuilder

	// Message Overrides the error message for this error.
	//
	// In built in implementation, If args are supplied, fmt.Sprintf will be called with s as base string.
	Message(s string, args ...any) ErrorBuilder

	// Error Sets the origin error for ErrorBuilder. Very unlikely to need to set this because Maleo.Wrap already uses the error.
	// But the api is available to set the origin error.
	Error(err error) ErrorBuilder

	// Context Sets additional data that will enrich how the error will look.
	//
	// The input is key-value format. The odd index will be used as key and the even index will be used as value.
	//
	// Key if not a string will be converted to string using fmt.Sprint.
	//
	// Example:
	//
	// 	maleo.Wrap(err).Code(400).Context("count", 123, "username", "kilua", "ranking", 5).Freeze()
	Context(ctx ...any) ErrorBuilder

	// Key Sets the key for this error. This is how the Messengers will use to identify if an error is the same as previous or not.
	//
	// Usually by not setting the key, The Messenger will generate their own.
	Key(key string, args ...any) ErrorBuilder

	// Caller Sets the caller for this error.
	Caller(c Caller) ErrorBuilder

	// Level Sets the level for this error.
	Level(lvl Level) ErrorBuilder

	// Time Sets the time for this error.
	Time(t time.Time) ErrorBuilder

	// Freeze this ErrorBuilder, preventing further mutations and set this ErrorBuilder into proper error.
	//
	// The returned Error is safe for multithreading usage because of its immutable nature.
	Freeze() Error

	// Log this error. Implicitly calls .Freeze() on this ErrorBuilder.
	Log(ctx context.Context) Error

	// Notify Notifies this error to Messengers. Implicitly calls .Freeze() on this ErrorBuilder.
	Notify(ctx context.Context, opts ...MessageOption) Error
}

ErrorBuilder is an interface to create customizable error.

ErrorBuilder by itself is not an error type. You have to call .Freeze() method to create proper Error type.

func Bail

func Bail(msg string, args ...any) ErrorBuilder

Bail creates a new ErrorBuilder from simple messages.

If args are not empty, msg will be fed into fmt.Errorf along with the args. Otherwise, msg will be fed into `errors.New()`.

NOTE: When you call .Log(ctx) or .Notify(ctx) and context is attached with a Maleo instance, the error will be logged or notified using that Maleo instance, instead of the global Maleo instance.

func Wrap

func Wrap(err error, msgAndArgs ...any) ErrorBuilder

Wrap the error. The returned ErrorBuilder may be appended with values. Call .Freeze() method to turn this into proper error. Or call .Log() or .Notify() to implicitly freeze the error and do actual stuffs.

NOTE: When you call .Log(ctx) or .Notify(ctx) and context is attached with a Maleo instance, the error will be logged or notified using that Maleo instance, instead of the global Maleo instance.

Example:

if err != nil {
  return maleo.Wrap(err, "something went wrong: %s", reason).Freeze()
}

Example with Log:

if err != nil {
  return maleo.Wrap(err, "something went wrong: %s", reason).Log(ctx)
}

Example with Notify:

if err != nil {
  return maleo.Wrap(err, "something went wrong").Notify(ctx)
}

Example with Notify and Log:

if err != nil {
  return maleo.Wrap(err, "something went wrong").Log(ctx).Notify(ctx)
}

Example with inline Maleo instance, instead of using global:

myCustomMaleo := maleo.New()
ctx = maleo.ContextWithMaleo(ctx, myCustomMaleo)
if err != nil {
  return maleo.Wrap(err, "something went wrong").Log(ctx).Notify(ctx)
}

type ErrorConstructor

type ErrorConstructor interface {
	ConstructError(*ErrorConstructorContext) ErrorBuilder
}

type ErrorConstructorContext

type ErrorConstructorContext struct {
	Err            error
	Caller         Caller
	MessageAndArgs []any
	Maleo          *Maleo
}

type ErrorConstructorFunc

type ErrorConstructorFunc func(*ErrorConstructorContext) ErrorBuilder

func (ErrorConstructorFunc) ConstructError

type ErrorMessageConstructorFunc

type ErrorMessageConstructorFunc func(err Error, param *MessageParameters) MessageContext

func (ErrorMessageConstructorFunc) BuildErrorMessageContext

func (f ErrorMessageConstructorFunc) BuildErrorMessageContext(err Error, param *MessageParameters) MessageContext

type ErrorMessageContextConstructor

type ErrorMessageContextConstructor interface {
	BuildErrorMessageContext(err Error, param *MessageParameters) MessageContext
}

type ErrorNode

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

ErrorNode is the implementation of the Error interface.

func (*ErrorNode) Caller

func (e *ErrorNode) Caller() Caller

Caller Gets the caller of this type.

func (*ErrorNode) Code

func (e *ErrorNode) Code() int

Code Gets the original code of the type.

func (*ErrorNode) CodeBlockJSON

func (e *ErrorNode) CodeBlockJSON() ([]byte, error)

func (*ErrorNode) Context

func (e *ErrorNode) Context() []any

Context Gets the context of this type.

func (*ErrorNode) Error

func (e *ErrorNode) Error() string

func (*ErrorNode) HTTPCode

func (e *ErrorNode) HTTPCode() int

HTTPCode Gets HTTP Status Code for the type.

func (*ErrorNode) Key

func (e *ErrorNode) Key() string

func (*ErrorNode) Level

func (e *ErrorNode) Level() Level

func (*ErrorNode) Log

func (e *ErrorNode) Log(ctx context.Context) Error

Log this error.

func (*ErrorNode) MarshalJSON

func (e *ErrorNode) MarshalJSON() ([]byte, error)

func (*ErrorNode) Message

func (e *ErrorNode) Message() string

Message Gets the Message of the type.

func (*ErrorNode) Notify

func (e *ErrorNode) Notify(ctx context.Context, opts ...MessageOption) Error

Notify this error to Messengers.

func (*ErrorNode) Service

func (e *ErrorNode) Service() Service

func (*ErrorNode) Time

func (e *ErrorNode) Time() time.Time

func (*ErrorNode) Unwrap

func (e *ErrorNode) Unwrap() error

Unwrap Returns the error that is wrapped by this error. To be used by errors.Is and errors.As functions from errors library.

func (*ErrorNode) WriteError

func (e *ErrorNode) WriteError(w LineWriter)

WriteError Writes the error.Error to the writer instead of being allocated as value.

type ErrorStack

type ErrorStack struct {
	Caller Caller
	Error  error
}

type ErrorWriter

type ErrorWriter interface {
	// WriteError Writes the error.Error to the writer instead of being allocated as value.
	WriteError(w LineWriter)
}

type F

type F = Fields

F Alias to maleo.Fields.

type Fields

type Fields map[string]any

func (Fields) Summary

func (f Fields) Summary() string

Summary Returns a short summary of this type.

func (Fields) WriteSummary

func (f Fields) WriteSummary(w LineWriter)

WriteSummary Writes the Summary() string to the writer instead of being allocated as value.

type FilterMessengersFunc

type FilterMessengersFunc = func(Messenger) bool

type HTTPCodeHint

type HTTPCodeHint interface {
	// HTTPCode Gets HTTP Status Code for the type.
	HTTPCode() int
}

type InitOption

type InitOption interface {
	// contains filtered or unexported methods
}

type InitOptionBuilder

type InitOptionBuilder []InitOption

func (InitOptionBuilder) CallerDepth

func (i InitOptionBuilder) CallerDepth(depth int) InitOptionBuilder

func (InitOptionBuilder) DefaultMessageOptions

func (i InitOptionBuilder) DefaultMessageOptions(opts ...MessageOption) InitOptionBuilder

DefaultMessageOptions overrides the default options for messages.

func (InitOptionBuilder) Logger

Logger sets the logger for Maleo.

func (InitOptionBuilder) Messengers

func (i InitOptionBuilder) Messengers(messengers ...Messenger) InitOptionBuilder

Messengers sets the default messengers for Maleo.

func (InitOptionBuilder) Name

Name sets the name of the Maleo instance. This is used for managing the messengers.

Only useful if you set this Maleo instance as a Messenger for other Maleo instances.

type InitOptionFunc

type InitOptionFunc func(*Maleo)

type KVString added in v0.1.1

type KVString struct {
	Key, Value string
}

type KeyHint

type KeyHint interface {
	// Key returns the key for this type.
	Key() string
}

type Level

type Level int8

Level represents the level severity of the message.

const (
	DebugLevel Level = iota - 1
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
	PanicLevel
)

func (Level) String

func (l Level) String() string

type LevelHint

type LevelHint interface {
	// Level returns the level of this type.
	Level() Level
}

type LineWriter

type LineWriter interface {
	io.Writer
	io.StringWriter
	// WriteLineBreak Writes a predetermined new line character(s) to the writer.
	WriteLineBreak()
	// WritePrefix Writes a predetermined prefix to the writer.
	WritePrefix()
	// WriteSuffix Writes a predetermined suffix to the writer.
	WriteSuffix()
	// WriteIndent Writes Indentation characters.
	WriteIndent()
	// GetLineBreak Returns the pre-determined line break characters.
	GetLineBreak() string
	// GetPrefix Returns the pre-determined prefix.
	GetPrefix() string
	// GetSuffix Returns the pre-determined suffix.
	GetSuffix() string
	// GetIndentation Returns the pre-determined indentation.
	GetIndentation() string
}

type LineWriterBuilder

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

func NewLineWriter

func NewLineWriter(writer io.Writer) *LineWriterBuilder

NewLineWriter Creates a new LineWriterBuilder. You have to call .Build() to actually use LineWriter.

func (*LineWriterBuilder) Build

func (builder *LineWriterBuilder) Build() LineWriter

Build Turn this writer into proper LineWriter.

func (*LineWriterBuilder) Indent

func (builder *LineWriterBuilder) Indent(s string) *LineWriterBuilder

Indent Sets the Indentation.

func (*LineWriterBuilder) LineBreak

func (builder *LineWriterBuilder) LineBreak(s string) *LineWriterBuilder

LineBreak Sets the Linebreak character(s).

func (*LineWriterBuilder) Prefix

func (builder *LineWriterBuilder) Prefix(s string) *LineWriterBuilder

Prefix Sets the Prefix.

func (*LineWriterBuilder) Suffix

func (builder *LineWriterBuilder) Suffix(s string) *LineWriterBuilder

Suffix Sets the Suffix.

type Logger

type Logger interface {
	Log(ctx context.Context, entry Entry)
	LogError(ctx context.Context, err Error)
}

type Maleo

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

func Global

func Global() *Maleo

Global returns the global Maleo instance.

To get a copy of the global Maleo instance, use maleo.Global().Clone()

Do not attach Global instance to struct members or somewhere long lived, call Clone() first and use the cloned instance instead.

Cloned Maleo instance will ignore Maleo instances attached to context.

func MaleoFromContext added in v0.4.0

func MaleoFromContext(ctx context.Context) *Maleo

MaleoFromContext retrieves Maleo instance from context.

Returns nil if there is no Maleo instance attached.

func New added in v0.2.0

func New(service Service, opts ...InitOption) *Maleo

New creates a new Maleo instance.

func (*Maleo) Bail

func (m *Maleo) Bail(msg string, args ...any) ErrorBuilder

Bail creates a new ErrorBuilder from simple messages.

If args is not empty, msg will be fed into fmt.Errorf along with the args. Otherwise, msg will be fed into `errors.New()`.

func (*Maleo) BailFreeze

func (m *Maleo) BailFreeze(msg string, args ...any) Error

BailFreeze creates new immutable Error from simple messages.

If args is not empty, msg will be fed into fmt.Errorf along with the args. Otherwise, msg will be fed into `errors.New()`.

func (*Maleo) Clone added in v0.4.1

func (m *Maleo) Clone() *Maleo

Clone creates a new Maleo instance with the same parameters as the current one.

The new Maleo instance will have the same name, logger, engine, and caller depth, but marked as non-global.

func (*Maleo) Log

func (m *Maleo) Log(ctx context.Context, entry Entry)

Log implements the Logger interface. Maleo instance itself can be a Logger for other Maleo instance.

If ctx contains a Maleo instance, and current instance is a Global one, it will be used instead.

func (*Maleo) LogError

func (m *Maleo) LogError(ctx context.Context, err Error)

LogError implements the Logger interface. Maleo instance itself can be a Logger for other Maleo instance.

If ctx contains a Maleo instance, and current instance is a Global one, it will be used instead.

func (*Maleo) Name

func (m *Maleo) Name() string

Name implements the Messenger interface. If name is not set on initialization, it will return Service.String().

func (*Maleo) NewEntry

func (m *Maleo) NewEntry(msg string, args ...any) EntryBuilder

NewEntry Creates a new EntryBuilder. The returned EntryBuilder may be appended with values.

func (*Maleo) Notify

func (m *Maleo) Notify(ctx context.Context, entry Entry, parameters ...MessageOption)

Notify Sends the Entry to Messengers.

func (*Maleo) NotifyError

func (m *Maleo) NotifyError(ctx context.Context, err Error, parameters ...MessageOption)

NotifyError sends the Error to Messengers.

func (*Maleo) Register

func (m *Maleo) Register(messengers ...Messenger)

Register registers a new messenger to the default parameters.

func (*Maleo) RegisterBenched

func (m *Maleo) RegisterBenched(messengers ...Messenger)

RegisterBenched registers a new messenger to the default benched parameters.

Benched messengers will not be used on normal notify calls. They have to be called explicitly using .Include() or .Filter() options.

func (*Maleo) SendMessage

func (m *Maleo) SendMessage(ctx context.Context, msg MessageContext)

SendMessage implements the Messenger interface. Maleo instance itself can be a Messenger for other Maleo instances.

Note that SendMessage for Maleo only support Messengers that are set in initialization or call Maleo.Register.

func (*Maleo) Service

func (m *Maleo) Service() Service

func (*Maleo) SetEngine

func (m *Maleo) SetEngine(engine Engine)

func (*Maleo) SetLogger

func (m *Maleo) SetLogger(logger Logger)

func (*Maleo) Wait

func (m *Maleo) Wait(ctx context.Context) error

Wait implements the Messenger interface. Maleo instance itself can be a Messenger.

func (*Maleo) Wrap

func (m *Maleo) Wrap(err error, msgAndArgs ...any) ErrorBuilder

Wrap works like exported maleo.Wrap, but at the scope of this Maleo instance instead.

func (*Maleo) WrapFreeze

func (m *Maleo) WrapFreeze(err error, msgAndArgs ...any) Error

WrapFreeze works like exported maleo.WrapFreeze, but at the scope of this Maleo instance instead.

type MessageContext

type MessageContext interface {
	HTTPCodeHint
	CodeHint
	MessageHint
	CallerHint
	KeyHint
	LevelHint
	ServiceHint
	ContextHint
	TimeHint
	// Err returns the error item. May be nil if message contains no error.
	Err() error
	// ForceSend If true, Sender asks for this message to always be send at the earliest possible.
	ForceSend() bool
	// Cooldown returns non-zero value if Sender asks for this message to be sent after this duration.
	Cooldown() time.Duration
	// Maleo Gets the Maleo instance that created this MessageContext.
	Maleo() *Maleo
}

MessageContext is the context of a message.

It holds the message and data that can be sent to the Messenger's target.

type MessageContextConstructorFunc

type MessageContextConstructorFunc func(entry Entry, param *MessageParameters) MessageContext

func (MessageContextConstructorFunc) BuildEntryMessageContext

func (m MessageContextConstructorFunc) BuildEntryMessageContext(entry Entry, param *MessageParameters) MessageContext

type MessageHint

type MessageHint interface {
	// Message returns the message of the type.
	Message() string
}

type MessageOption

type MessageOption interface {
	Apply(*MessageParameters)
}

type MessageOptionBuilder

type MessageOptionBuilder []MessageOption

func (MessageOptionBuilder) Apply

func (m MessageOptionBuilder) Apply(parameters *MessageParameters)

func (MessageOptionBuilder) Cooldown

Cooldown overrides the base cooldown for the message for the Messengers.

The implementation differs per Messenger and may instead ignore this value completely. But the builtin Messengers will use this value as the base cooldown before multiplying it with the cooldown multiplier for every same message sent.

e.g. setting this cooldown to 5 seconds and the cooldown multiplier to 2 will result in the following cooldowns:

1st message: 5 seconds

2nd message: 10 seconds

3rd message: 20 seconds

4th message: 40 seconds

and so on.

Setting this option to 0 or negative value will result in the Messenger using the default cooldown.

Setting this option to initialize Maleo will set the default cooldown for all messages.

func (MessageOptionBuilder) Exclude

Exclude removes the Messengers that match the given filter. Does not affect the benched Messengers.

func (MessageOptionBuilder) ExcludeName

func (m MessageOptionBuilder) ExcludeName(name ...string) MessageOptionBuilder

ExcludeName removes the Messengers that have the exact given name(s). Does not affect the benched Messengers.

func (MessageOptionBuilder) ExcludePrefix

func (m MessageOptionBuilder) ExcludePrefix(prefix string) MessageOptionBuilder

ExcludePrefix removes the Messengers that match the given filter. Does not affect the benched Messengers.

func (MessageOptionBuilder) ExcludeSuffix

func (m MessageOptionBuilder) ExcludeSuffix(suffix string) MessageOptionBuilder

ExcludeSuffix removes the Messengers that match the given filter. Does not affect the benched Messengers.

func (MessageOptionBuilder) Filter

func (m MessageOptionBuilder) Filter(filterMessenger, filterBenched FilterMessengersFunc) MessageOptionBuilder

Filter filters the Messengers to only include those that match the given filter.

It's safe to use nil for either or both arguments, if you don't wish to filter. They are merely ignored when nil.

The result of two filters are then combined for Maleo to call.

func (MessageOptionBuilder) FilterName

func (m MessageOptionBuilder) FilterName(names ...string) MessageOptionBuilder

FilterName filters the Messengers to only include those that have the exact given name(s).

This option also include Messengers that are benched into the list of Messengers to be called if they match the name.

This option is ignored when you give empty names.

func (MessageOptionBuilder) ForceSend

ForceSend asks the Messengers to send the message immediately. Typically, the implementation of Messengers will still take account of Messenger's own rate limits, so the message may still be delayed or dropped. What the Messenger will do however is to ignore any message cooldowns.

So if the Messenger has a rate limit of 1 second per message, ForceSend will send the Message after 1 second of last message sent, regardless of the cooldown.

Note: Setting this option when initializing Maleo will basically ask the Messengers for *all* messages to be sent immediately.

func (MessageOptionBuilder) Include

func (m MessageOptionBuilder) Include(messengers ...Messenger) MessageOptionBuilder

Include adds extra Messengers to the list of Messengers to be called.

func (MessageOptionBuilder) IncludeBenched

func (m MessageOptionBuilder) IncludeBenched() MessageOptionBuilder

IncludeBenched adds the Messengers that are benched to the list of Messengers to be called.

func (MessageOptionBuilder) IncludeBenchedContains

func (m MessageOptionBuilder) IncludeBenchedContains(str string) MessageOptionBuilder

IncludeBenchedContains includes the benched Messengers that have the given string in their name to be used by Maleo.

func (MessageOptionBuilder) IncludeBenchedFilter

IncludeBenchedFilter filters the benched Messengers to only include those that match the given filter.

func (MessageOptionBuilder) IncludeBenchedName

func (m MessageOptionBuilder) IncludeBenchedName(names ...string) MessageOptionBuilder

IncludeBenchedName includes the benched Messengers that have the exact given name(s).

func (MessageOptionBuilder) IncludeBenchedPrefix

func (m MessageOptionBuilder) IncludeBenchedPrefix(prefix string) MessageOptionBuilder

IncludeBenchedPrefix includes the benched Messengers have the given prefix in their name to be used by Maleo.

func (MessageOptionBuilder) IncludeBenchedSuffix

func (m MessageOptionBuilder) IncludeBenchedSuffix(suffix string) MessageOptionBuilder

IncludeBenchedSuffix includes the benched Messengers have the given suffix in their name to be used by Maleo.

func (MessageOptionBuilder) Messengers

func (m MessageOptionBuilder) Messengers(messengers ...Messenger) MessageOptionBuilder

Messengers set the Messengers you want to use and ignores the rest for this message.

Using this option when initializing Maleo will register the Messenger as default Messengers for Maleo.

Alternatively, use Maleo.Register or Maleo.RegisterBenched to register Messengers.

type MessageOptionFunc

type MessageOptionFunc func(*MessageParameters)

func (MessageOptionFunc) Apply

func (m MessageOptionFunc) Apply(parameters *MessageParameters)

type MessageParameters

type MessageParameters struct {
	ForceSend  bool
	Messengers Messengers
	Benched    Messengers
	Cooldown   time.Duration
	Maleo      *Maleo
}

type Messenger

type Messenger interface {
	// Name Returns the name of the Messenger.
	Name() string
	// SendMessage Send Message to Messengers.
	SendMessage(ctx context.Context, msg MessageContext)

	// Wait Waits until all message in the queue or until given channel is received.
	//
	// Implementer must exit the function as soon as possible when this ctx is canceled.
	Wait(ctx context.Context) error
}

type Messengers

type Messengers []Messenger

func (Messengers) Filter

Filter Filters the Messengers.

func (Messengers) SendMessage

func (m Messengers) SendMessage(ctx context.Context, msg MessageContext)

SendMessage Send Message to Messengers.

func (Messengers) Wait

func (m Messengers) Wait(ctx context.Context) error

Wait Waits until all message in the queue or until given channel is received.

type NoopLogger

type NoopLogger struct{}

NoopLogger that does nothing. The default logger that Maleo uses.

func (NoopLogger) Log

func (NoopLogger) Log(ctx context.Context, entry Entry)

func (NoopLogger) LogError

func (NoopLogger) LogError(ctx context.Context, err Error)

type NoopTraceCapturer added in v0.1.1

type NoopTraceCapturer struct{}

func (NoopTraceCapturer) CaptureTrace added in v0.1.1

func (n NoopTraceCapturer) CaptureTrace(context.Context) []KVString

type Service

type Service struct {
	Name        string `json:"name,omitempty"`
	Environment string `json:"environment,omitempty"`
	Type        string `json:"type,omitempty"`
	Version     string `json:"version,omitempty"`
}

Service represents the service information.

func (Service) String

func (s Service) String() string

String returns the string representation of the service information.

Returns in the format of `name-version-type-environment`. If any field is empty, it will be omitted.

type ServiceHint

type ServiceHint interface {
	// Service returns the service information.
	Service() Service
}

type Summary

type Summary interface {
	// Summary Returns a short summary of the implementer.
	Summary() string
}

type SummaryWriter

type SummaryWriter interface {
	// WriteSummary Writes the Summary() string to the writer instead of being allocated as value.
	WriteSummary(w LineWriter)
}

type TestingJSONLogger

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

func NewTestingJSONLogger

func NewTestingJSONLogger() *TestingJSONLogger

NewTestingJSONLogger returns a very basic logger for testing purposes.

func (*TestingJSONLogger) Bytes

func (t *TestingJSONLogger) Bytes() []byte

Bytes returns the accumulated bytes.

func (*TestingJSONLogger) Log

func (t *TestingJSONLogger) Log(_ context.Context, entry Entry)

Log implements maleo.Logger.

func (*TestingJSONLogger) LogError

func (t *TestingJSONLogger) LogError(_ context.Context, err Error)

LogError implements maleo.Logger.

func (*TestingJSONLogger) MarshalJSON

func (t *TestingJSONLogger) MarshalJSON() ([]byte, error)

func (*TestingJSONLogger) PrettyPrint

func (t *TestingJSONLogger) PrettyPrint()

func (*TestingJSONLogger) Reset

func (t *TestingJSONLogger) Reset()

Reset resets the buffer to be empty.

func (*TestingJSONLogger) String

func (t *TestingJSONLogger) String() string

String returns the accumulated bytes as string.

type TimeHint

type TimeHint interface {
	// Time returns the time of this type.
	Time() time.Time
}

type TraceCapturer added in v0.1.1

type TraceCapturer interface {
	// CaptureTrace captures the trace from the context.
	CaptureTrace(ctx context.Context) []KVString
}

type TraceCapturerFunc added in v0.1.1

type TraceCapturerFunc func(ctx context.Context) []KVString

func (TraceCapturerFunc) CaptureTrace added in v0.1.1

func (f TraceCapturerFunc) CaptureTrace(ctx context.Context) []KVString

type UnwrapError

type UnwrapError interface {
	// Unwrap Returns the error that is wrapped by this error. To be used by errors.Is and errors.As functions from errors library.
	Unwrap() error
}

Directories

Path Synopsis
bucket module
maleominio Module
maleominio-v7 Module
maleos3-v2 Module
loader module
locker module
maleodiscord module
maleohttp module
maleozap module
queue module

Jump to

Keyboard shortcuts

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