logwrap

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 14, 2022 License: Apache-2.0 Imports: 7 Imported by: 16

README

Shimmering Bee: Log Wrap

license standard-readme compliant Actions Status

Log wrapper providing syntactic sugar for structured logging, including context based persistent options and implementations for common logging systems.

Table of Contents

Background

Install

Add an import and most IDEs will go get automatically, if it doesn't go build will fetch.

import "github.com/shimmeringbee/logwrap"

Usage

This libraries API is unstable and should not yet be relied upon.

Maintainers

@pwood

Contributing

Feel free to dive in! Open an issue or submit PRs.

All Shimmering Bee projects follow the Contributor Covenant Code of Conduct.

License

Copyright 2019-2020 Shimmering Bee Contributors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Index

Constants

View Source
const ParentSegmentIDField = "parentSegmentID"

ParentSegmentIDField is the name of the field which contains this segments parent ID.

View Source
const SegmentEndValue = "end"

SegmentEndValue is the value placed in the SegmentField denoting the end of a segment.

View Source
const SegmentField = "segment"

SegmentField is the name of the field which a segment will place the start and end markers in.

View Source
const SegmentIDField = "segmentID"

SegmentIDField is the name of the field which contains the segment ID.

View Source
const SegmentStartValue = "start"

SegmentStartValue is the value placed in the SegmentField denoting the start of a segment.

View Source
const SourceTraceField = "sourceTrace"

SourceTraceField is the name of the field that the SourceTrace option will place its data in.

Variables

This section is empty.

Functions

func SequenceAsField

func SequenceAsField(message *Message)

SequenceAsField is an option which copies the message sequence to the fields.

func SourceAsField

func SourceAsField(message *Message)

SourceAsField is an option which copies the message source to the fields, useful for log implementations that do not natively support source values.

func SourceTrace

func SourceTrace(message *Message)

SourceTrace inserts the file and line number of the file that Log was called at. This routine searches for the frame pointer before the first call to the Logger object. The search is used rather than static in case the option is used in a post option filter, and to allow utility wrappers such as LogInfo instead of `Log(...,...,Level(Info))`.

Types

type Impl

type Impl func(context.Context, Message)

Impl is the interface for the actual implementation of logging to implement.

The default recommendation is that implementations should not block during execution. The implementation should make use of go concurrency techniques to remove blocking code from calling functions go routine.

Should an implementation block by design (such as assured delivery of logs), this should be made explicitly clear in any documentation.

Implementations should obey the semantics of Panic and Fatal levels, panic()ing and os.Exit(-1) respectively after the log has been made.

type List

type List map[string]interface{}

List is syntactic sugar to allow users to `Data(List{"key": "value"})`.

type LogLevel

type LogLevel uint

LogLevel is the log level type.

const (
	// Panic level, the error encountered immediately panics the application.
	Panic LogLevel = iota
	// Fatal level, a severe enough issue has occurred the the application can no longer continue.
	Fatal
	// Error level, a severe issue has been encountered, but the application has recovered.
	Error
	// Warn level, an issue has occurred which has not caused a operational issue, but should not have happened.
	Warn
	// Info level, general information about the applications progress, decisions or checkpoints reached.
	Info
	// Debug level, verbose logging usually only needed by a operator when fault finding.
	Debug
	// Trace level, extreme diagnostics reporting very fine details, usually only needed by developers.
	Trace
)

Possible log levels that messages can be made against.

func (LogLevel) String

func (l LogLevel) String() string

String provides a text description of the level.

type Logger

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

Logger is the representation of a stream of logs, it should always be instantiated with `New`.

func New

func New(i Impl) Logger

New constructs a new logger, taking the backend implement which will actually log.

func (Logger) AddOptionsToContext

func (l Logger) AddOptionsToContext(ctx context.Context, options ...Option) context.Context

AddOptionsToContext add default Option's to a context for this specific logger (i.e. two loggers will have different options on the same context). These are always processed first, before any Option's provided during Log.

func (*Logger) AddOptionsToLogger

func (l *Logger) AddOptionsToLogger(options ...Option)

AddOptionsToLogger adds default options to the logger which do not vary by implementation, and are applied first before any context or log specific messages.

func (Logger) Debug

func (l Logger) Debug(ctx context.Context, message string, options ...Option)

Debug is an alias for LogDebug.

func (Logger) Error

func (l Logger) Error(ctx context.Context, message string, options ...Option)

Error is an alias for LogError.

func (Logger) Fatal

func (l Logger) Fatal(ctx context.Context, message string, options ...Option)

Fatal is an alias for LogFatal.

func (Logger) Info

func (l Logger) Info(ctx context.Context, message string, options ...Option)

Info is an alias for LogInfo.

func (Logger) Log

func (l Logger) Log(ctx context.Context, message string, options ...Option)

Log processes and logs the provided message, applying any options which have been stored in the context first and then those passed into Log.

func (Logger) LogDebug

func (l Logger) LogDebug(ctx context.Context, message string, options ...Option)

LogDebug calls Log while appending Level(Debug) as an option.

func (Logger) LogError

func (l Logger) LogError(ctx context.Context, message string, options ...Option)

LogError calls Log while appending Level(Error) as an option.

func (Logger) LogFatal

func (l Logger) LogFatal(ctx context.Context, message string, options ...Option)

LogFatal calls Log while appending Level(Fatal) as an option.

func (Logger) LogInfo

func (l Logger) LogInfo(ctx context.Context, message string, options ...Option)

LogInfo calls Log while appending Level(Info) as an option.

func (Logger) LogPanic

func (l Logger) LogPanic(ctx context.Context, message string, options ...Option)

LogPanic calls Log while appending Level(Panic) as an option.

func (Logger) LogTrace

func (l Logger) LogTrace(ctx context.Context, message string, options ...Option)

LogTrace calls Log while appending Level(Trace) as an option.

func (Logger) LogWarn

func (l Logger) LogWarn(ctx context.Context, message string, options ...Option)

LogWarn calls Log while appending Level(Warn) as an option.

func (Logger) Panic

func (l Logger) Panic(ctx context.Context, message string, options ...Option)

Panic is an alias for LogPanic.

func (Logger) Segment

func (l Logger) Segment(pctx context.Context, message string, options ...Option) (context.Context, func())

Segment is used to wrap a section of a program, this can be used to demonstrate a group of logs are related. Segments can be nested and the `segmentID` and `parentSegmentId` fields can be used to reconstruct nested logs into a hierarchy.

An expected use of Segment might be as follows:

func submitToAPI(pctx context.Context) {
    ctx, end := logger.Segment(pctx, "api submission")
    defer end()
    //
    subCtx, subEnd := logger.Segment(ctx, "prepare api submission")
    request, err := // Prepare api submission
    logger.Log(subCtx, "preparation results", Datum("request": request))
    subEnd()
    //
    err := // Submit to api functional code
    if err != nil {
         logger.Log(ctx, "failed to submit to api", Err(err))
    }
}

This code would product log likes approximately like: * [INFO] api submission {"segment": "start", "segmentID": 1} * [INFO] prepare api submission {"segment": "start", "segmentID": 2, "parentSegmentId": 1} * [INFO] preparation results {"segmentID": 2, "parentSegmentId": 1, "request": <request object>} * [INFO] prepare api submission {"segment": "end", "segmentID": 2, "parentSegmentId": 1} * [INFO] api submission {"segment": "end", "segmentID": 1}

func (Logger) SegmentFn added in v0.1.2

func (l Logger) SegmentFn(pctx context.Context, message string, options ...Option) func(func(ctx context.Context) error) error

SegmentFn works similar to Segment, but returns a function that takes a new function to be called. This can be used to wrap calls with a Segment, removing the complexity of handling the end function of Segment. The function returned passes the new child context into the wrapped function.

For example, converting the Segment function example:

func submitToAPI(pctx context.Context) {
    ctx, end := logger.Segment(pctx, "api submission")
    defer end()
    //
    if err := logger.SegmentFn(ctx, "prepare api submission")(func(subCtx context.Context) error {
        request, err := // Prepare api submission
        logger.Log(subCtx, "preparation results", Datum("request": request))
    }); err != nil {
         logger.Log(ctx, "failed to submit to api", Err(err))
    }
}

It is expected that errors in the returned function are actual problems, as it will log the error. It is not expected that segments will be used where the error is unimportant.

func (Logger) Trace

func (l Logger) Trace(ctx context.Context, message string, options ...Option)

Trace is an alias for LogTrace.

func (Logger) Warn

func (l Logger) Warn(ctx context.Context, message string, options ...Option)

Warn is an alias for LogWarn.

type Message

type Message struct {
	// Level of log message.
	Level LogLevel
	// Message is the human readable version of the message.
	Message string
	// Data are a free form map of data to log, usually for structured logging.
	Data map[string]interface{}
	// Timestamp at which the log was made.
	Timestamp time.Time
	// Sequence is a monotonic sequence number, used to determine log order with high frequency/low interval logs.
	Sequence uint64
	// Source is the name of the part of a system the message is emitted from
	Source string
}

Message structure is the struct sent to a logging implementation, it includes all fields.

type Option

type Option func(*Message)

Option is an interface for a option a Log call can take, adding or modifying data on a Message.

func Data

func Data(list List) Option

Data is an option which takes a list of options and adds them to a message.

func Datum

func Datum(key string, value interface{}) Option

Datum is an option which adds a single key/value to the data of the message.

func Err

func Err(err error) Option

Err is syntactic sugar to place errors in a messages fields.

func Level

func Level(l LogLevel) Option

Level is an option which sets the messages level.

func Source

func Source(source string) Option

Source is an option to populate the source field of a message.

func Trail

func Trail(s string) Option

Trail builds a period delimited path, useful for assigning hierarchical identifiers to log messages.

type SourceLocation

type SourceLocation struct {
	Function string
	File     string
	Line     int
}

SourceLocation is a representation of where the log line was called from.

Directories

Path Synopsis
impl
tee

Jump to

Keyboard shortcuts

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