log

package
v0.0.0-...-ce94876 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2019 License: MIT, MIT Imports: 17 Imported by: 0

README

go-log

standard-readme compliant GoDoc Build Status

The logging library used by go-ipfs

It currently uses a modified version of go-logging to implement the standard printf-style log output.

Install

go get github.com/ipfs/go-log

Usage

Once the pacakge is imported under the name logging, an instance of EventLogger can be created like so:

var log = logging.Logger("subsystem name")

It can then be used to emit log messages, either plain printf-style messages at six standard levels or structured messages using Start, StartFromParentState, Finish and FinishWithErr methods.

Example

func (s *Session) GetBlock(ctx context.Context, c *cid.Cid) (blk blocks.Block, err error) {

    // Starts Span called "Session.GetBlock", associates with `ctx`
    ctx = log.Start(ctx, "Session.GetBlock")

    // defer so `blk` and `err` can be evaluated after call
    defer func() {
        // tag span associated with `ctx`
        log.SetTags(ctx, map[string]interface{}{
            "cid": c,
            "block", blk,
        })
        // if err is non-nil tag the span with an error
        log.FinishWithErr(ctx, err)
    }()

    if shouldStartSomething() {
        // log message on span associated with `ctx`
        log.LogKV(ctx, "startSomething", true)
    }
  ...
}

Tracing

go-log wraps the opentracing-go methods - StartSpan, Finish, LogKV, and SetTag.

go-log implements its own tracer - loggabletracer - based on the basictracer-go implementation. If there is an active WriterGroup the loggabletracer will record span data to the WriterGroup. An example of this can be seen in the log tail command of go-ipfs.

Third party tracers may be used by calling opentracing.SetGlobalTracer() with your desired tracing implementation. An example of this can be seen using the go-jaeger-plugin and the go-ipfs tracer plugin

Contribute

Feel free to join in. All welcome. Open an issue!

This repository falls under the IPFS Code of Conduct.

Want to hack on IPFS?

License

MIT

Documentation

Overview

Package log is the logging library used by IPFS (https://github.com/ipfs/go-ipfs). It uses a modified version of https://godoc.org/github.com/whyrusleeping/go-logging .

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNoSuchLogger = errors.New("Error: No such logger")

ErrNoSuchLogger is returned when the util pkg is asked for a non existant logger

View Source
var LogFormats = map[string]string{
	"nocolor": "%{time:2006-01-02 15:04:05.000000} %{level} %{module} %{shortfile}: %{message}",
	"color": ansiGray + "%{time:15:04:05.000} %{color}%{level:5.5s} " + ansiBlue +
		"%{module:10.10s}: %{color:reset}%{message} " + ansiGray + "%{shortfile}%{color:reset}",
}

LogFormats defines formats for logging (i.e. "color")

Functions

func ContextWithLoggable

func ContextWithLoggable(ctx context.Context, l Loggable) context.Context

ContextWithLoggable returns a derived context which contains the provided Loggable. Any Events logged with the derived context will include the provided Loggable.

func FormatRFC3339

func FormatRFC3339(t time.Time) string

FormatRFC3339 returns the given time in UTC with RFC3999Nano format.

func GetSubsystems

func GetSubsystems() []string

GetSubsystems returns a slice containing the names of the current loggers

func SetAllLoggers

func SetAllLoggers(lvl logging.Level)

SetAllLoggers changes the logging.Level of all loggers to lvl

func SetDebugLogging

func SetDebugLogging()

SetDebugLogging calls SetAllLoggers with logging.DEBUG

func SetLogLevel

func SetLogLevel(name, level string) error

SetLogLevel changes the log level of a specific subsystem name=="*" changes all subsystems

func SetupLogging

func SetupLogging()

SetupLogging will initialize the logger backend and set the flags. TODO calling this in `init` pushes all configuration to env variables - move it out of `init`? then we need to change all the code (js-ipfs, go-ipfs) to call this explicitly - have it look for a config file? need to define what that is

Types

type EventInProgress

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

DEPRECATED EventInProgress represent and event which is happening

func (*EventInProgress) Append

func (eip *EventInProgress) Append(l Loggable)

DEPRECATED use `LogKV` or `SetTag` Append adds loggables to be included in the call to Done

func (*EventInProgress) Close

func (eip *EventInProgress) Close() error

DEPRECATED use `Finish` Close is an alias for done

func (*EventInProgress) Done

func (eip *EventInProgress) Done()

DEPRECATED use `Finish` Done creates a new Event entry that includes the duration and appended loggables.

func (*EventInProgress) DoneWithErr

func (eip *EventInProgress) DoneWithErr(err error)

DEPRECATED use `FinishWithErr` DoneWithErr creates a new Event entry that includes the duration and appended loggables. DoneWithErr accepts an error, if err is non-nil, it is set on the EventInProgress. Otherwise the logic is the same as the `Done()` method

func (*EventInProgress) SetError

func (eip *EventInProgress) SetError(err error)

DEPRECATED use `SetError(ctx, error)` SetError includes the provided error

type EventLogger

type EventLogger interface {
	StandardLogger

	// Event merges structured data from the provided inputs into a single
	// machine-readable log event.
	//
	// If the context contains metadata, a copy of this is used as the base
	// metadata accumulator.
	//
	// If one or more loggable objects are provided, these are deep-merged into base blob.
	//
	// Next, the event name is added to the blob under the key "event". If
	// the key "event" already exists, it will be over-written.
	//
	// Finally the timestamp and package name are added to the accumulator and
	// the metadata is logged.
	// DEPRECATED
	Event(ctx context.Context, event string, m ...Loggable)

	// DEPRECATED
	EventBegin(ctx context.Context, event string, m ...Loggable) *EventInProgress

	// Start starts an opentracing span with `name`, using
	// any Span found within `ctx` as a ChildOfRef. If no such parent could be
	// found, Start creates a root (parentless) Span.
	//
	// The return value is a context.Context object built around the
	// returned Span.
	//
	// Example usage:
	//
	//    SomeFunction(ctx context.Context, ...) {
	//        ctx := log.Start(ctx, "SomeFunction")
	//        defer log.Finish(ctx)
	//        ...
	//    }
	Start(ctx context.Context, name string) context.Context

	// StartFromParentState starts an opentracing span with `name`, using
	// any Span found within `ctx` as a ChildOfRef. If no such parent could be
	// found, StartSpanFromParentState creates a root (parentless) Span.
	//
	// StartFromParentState will attempt to deserialize a SpanContext from `parent`,
	// using any Span found within to continue the trace
	//
	// The return value is a context.Context object built around the
	// returned Span.
	//
	// An error is returned when `parent` cannot be deserialized to a SpanContext
	//
	// Example usage:
	//
	//    SomeFunction(ctx context.Context, bParent []byte) {
	//        ctx := log.StartFromParentState(ctx, "SomeFunction", bParent)
	//        defer log.Finish(ctx)
	//        ...
	//    }
	StartFromParentState(ctx context.Context, name string, parent []byte) (context.Context, error)

	// Finish completes the span associated with `ctx`.
	//
	// Finish() must be the last call made to any span instance, and to do
	// otherwise leads to undefined behavior.
	// Finish will do its best to notify (log) when used in correctly
	//		.e.g called twice, or called on a spanless `ctx`
	Finish(ctx context.Context)

	// FinishWithErr completes the span associated with `ctx` and also calls
	// SetErr if `err` is non-nil
	//
	// FinishWithErr() must be the last call made to any span instance, and to do
	// otherwise leads to undefined behavior.
	// FinishWithErr will do its best to notify (log) when used in correctly
	//		.e.g called twice, or called on a spanless `ctx`
	FinishWithErr(ctx context.Context, err error)

	// SetErr tags the span associated with `ctx` to reflect an error occured, and
	// logs the value `err` under key `error`.
	SetErr(ctx context.Context, err error)

	// LogKV records key:value logging data about an event stored in `ctx`
	// Eexample:
	//    log.LogKV(
	//        "error", "resolve failure",
	//        "type", "cache timeout",
	//        "waited.millis", 1500)
	LogKV(ctx context.Context, alternatingKeyValues ...interface{})

	// SetTag tags key `k` and value `v` on the span associated with `ctx`
	SetTag(ctx context.Context, key string, value interface{})

	// SetTags tags keys from the `tags` maps on the span associated with `ctx`
	// Example:
	//    log.SetTags(ctx, map[string]{
	//		"type": bizStruct,
	//      "request": req,
	//		})
	SetTags(ctx context.Context, tags map[string]interface{})

	// SerializeContext takes the SpanContext instance stored in `ctx` and Seralizes
	// it to bytes. An error is returned if the `ctx` cannot be serialized to
	// a bytes array
	SerializeContext(ctx context.Context) ([]byte, error)
}

EventLogger extends the StandardLogger interface to allow for log items containing structured metadata

Example
{
	log := EventLogger(nil)
	e := log.EventBegin(context.Background(), "dial")
	e.Done()
}
{
	log := EventLogger(nil)
	e := log.EventBegin(context.Background(), "dial")
	_ = e.Close() // implements io.Closer for convenience
}
Output:

func Logger

func Logger(system string) EventLogger

Logger retrieves an event logger by name

type Loggable

type Loggable interface {
	Loggable() map[string]interface{}
}

Loggable describes objects that can be marshalled into Metadata for logging

func Deferred

func Deferred(key string, f func() string) Loggable

Deferred returns a LoggableF where the execution of the provided function is deferred.

func Pair

func Pair(key string, l Loggable) Loggable

Pair returns a Loggable where key is paired to Loggable.

type LoggableF

type LoggableF func() map[string]interface{}

LoggableF converts a func into a Loggable

func (LoggableF) Loggable

func (l LoggableF) Loggable() map[string]interface{}

Loggable implements the Loggable interface by running the LoggableF function.

type LoggableMap

type LoggableMap map[string]interface{}

LoggableMap is just a generic map keyed by string. It implements the Loggable interface.

func (LoggableMap) Loggable

func (l LoggableMap) Loggable() map[string]interface{}

Loggable implements the Loggable interface for LoggableMap

type Metadata

type Metadata map[string]interface{}

Metadata is a convenience type for generic maps

func DeepMerge

func DeepMerge(b, a Metadata) Metadata

DeepMerge merges the second Metadata parameter into the first. Nested Metadata are merged recursively. Primitives are over-written.

func MetadataFromContext

func MetadataFromContext(ctx context.Context) (Metadata, error)

MetadataFromContext extracts Matadata from a given context's value.

func Metadatify

func Metadatify(i interface{}) (Metadata, error)

Metadatify converts maps into Metadata.

func (Metadata) JsonString

func (m Metadata) JsonString() (string, error)

JsonString returns the marshaled JSON string for the metadata.

func (Metadata) Loggable

func (m Metadata) Loggable() map[string]interface{}

Loggable implements the Loggable interface.

type StandardLogger

type StandardLogger interface {
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Panic(args ...interface{})
	Panicf(format string, args ...interface{})
	Warning(args ...interface{})
	Warningf(format string, args ...interface{})
}

StandardLogger provides API compatibility with standard printf loggers eg. go-logging

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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