loggables.go 1.87 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9 10 11
// Package loggables includes a bunch of transaltor functions for commonplace/stdlib
// objects. This is boilerplate code that shouldn't change much, and not sprinkled
// all over the place (i.e. gather it here).
//
// Note: it may make sense to put all stdlib Loggable functions in the eventlog
// package. Putting it here for now in case we don't want to polute it.
package loggables

import (
	"net"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"

14
	log "github.com/jbenet/go-ipfs/thirdparty/eventlog"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16

	peer "github.com/jbenet/go-ipfs/p2p/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
)

// NetConn returns an eventlog.Metadata with the conn addresses
func NetConn(c net.Conn) log.Loggable {
	return log.Metadata{
		"localAddr":  c.LocalAddr(),
		"remoteAddr": c.RemoteAddr(),
	}
}

// Error returns an eventlog.Metadata with an error
func Error(e error) log.Loggable {
	return log.Metadata{
		"error": e.Error(),
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33 34

// Dial metadata is metadata for dial events
35 36 37
func Dial(sys string, lid, rid peer.ID, laddr, raddr ma.Multiaddr) DeferredMap {
	m := DeferredMap{}
	m["subsystem"] = sys
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
	if lid != "" {
39
		m["localPeer"] = func() interface{} { return lid.Pretty() }
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41
	}
	if laddr != nil {
42
		m["localAddr"] = func() interface{} { return laddr.String() }
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44
	}
	if rid != "" {
45
		m["remotePeer"] = func() interface{} { return rid.Pretty() }
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47
	}
	if raddr != nil {
48
		m["remoteAddr"] = func() interface{} { return raddr.String() }
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49
	}
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	return m
}

// DeferredMap is a Loggable which may contained deffered values.
type DeferredMap map[string]interface{}

// Loggable describes objects that can be marshalled into Metadata for logging
func (m DeferredMap) Loggable() map[string]interface{} {
	m2 := map[string]interface{}{}
	for k, v := range m {

		if vf, ok := v.(func() interface{}); ok {
			// if it's a DeferredVal, call it.
			m2[k] = vf()

		} else {
			// else use the value as is.
			m2[k] = v
		}
	}
	return m2
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71
}