log.go 2.19 KB
Newer Older
1 2 3 4 5 6 7 8
package elog

import (
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-logging"
	"github.com/jbenet/go-ipfs/util"
)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
9 10
// EventLogger extends the StandardLogger interface to allow for log items
// containing structured metadata
11 12
type EventLogger interface {
	StandardLogger
Brian Tiger Chow's avatar
Brian Tiger Chow committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26

	// 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.
27
	Event(ctx context.Context, event string, m ...Loggable)
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
}

type StandardLogger interface {
	Critical(args ...interface{})
	Criticalf(format string, args ...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{})
	Notice(args ...interface{})
	Noticef(format string, args ...interface{})
	Panic(args ...interface{})
	Panicf(format string, args ...interface{})
	Warning(args ...interface{})
	Warningf(format string, args ...interface{})
}

// Logger retrieves a particular event logger
func Logger(system string) EventLogger {
	return &eventLogger{util.Logger(system)}
}

// eventLogger implements the EventLogger and wraps a go-logging Logger
type eventLogger struct {
	*logging.Logger
}

59
func (el *eventLogger) Event(ctx context.Context, event string, metadata ...Loggable) {
60 61 62 63 64 65
	existing, err := MetadataFromContext(ctx)
	if err != nil {
		existing = Metadata{}
	}
	accum := existing
	for _, datum := range metadata {
66
		accum = DeepMerge(accum, datum.Loggable())
67 68 69 70 71 72 73 74 75
	}
	accum["event"] = event

	str, err := accum.JsonString()
	if err != nil {
		return
	}
	el.Logger.Info(str)
}