github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/util/eventlog/loggables/loggables.go (about)

     1  // Package loggables includes a bunch of transaltor functions for commonplace/stdlib
     2  // objects. This is boilerplate code that shouldn't change much, and not sprinkled
     3  // all over the place (i.e. gather it here).
     4  //
     5  // Note: it may make sense to put all stdlib Loggable functions in the eventlog
     6  // package. Putting it here for now in case we don't want to polute it.
     7  package loggables
     8  
     9  import (
    10  	"net"
    11  
    12  	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
    13  
    14  	log "github.com/ipfs/go-ipfs/thirdparty/eventlog"
    15  
    16  	peer "github.com/ipfs/go-ipfs/p2p/peer"
    17  )
    18  
    19  // NetConn returns an eventlog.Metadata with the conn addresses
    20  func NetConn(c net.Conn) log.Loggable {
    21  	return log.Metadata{
    22  		"localAddr":  c.LocalAddr(),
    23  		"remoteAddr": c.RemoteAddr(),
    24  	}
    25  }
    26  
    27  // Error returns an eventlog.Metadata with an error
    28  func Error(e error) log.Loggable {
    29  	return log.Metadata{
    30  		"error": e.Error(),
    31  	}
    32  }
    33  
    34  // Dial metadata is metadata for dial events
    35  func Dial(sys string, lid, rid peer.ID, laddr, raddr ma.Multiaddr) DeferredMap {
    36  	m := DeferredMap{}
    37  	m["subsystem"] = sys
    38  	if lid != "" {
    39  		m["localPeer"] = func() interface{} { return lid.Pretty() }
    40  	}
    41  	if laddr != nil {
    42  		m["localAddr"] = func() interface{} { return laddr.String() }
    43  	}
    44  	if rid != "" {
    45  		m["remotePeer"] = func() interface{} { return rid.Pretty() }
    46  	}
    47  	if raddr != nil {
    48  		m["remoteAddr"] = func() interface{} { return raddr.String() }
    49  	}
    50  	return m
    51  }
    52  
    53  // DeferredMap is a Loggable which may contained deffered values.
    54  type DeferredMap map[string]interface{}
    55  
    56  // Loggable describes objects that can be marshalled into Metadata for logging
    57  func (m DeferredMap) Loggable() map[string]interface{} {
    58  	m2 := map[string]interface{}{}
    59  	for k, v := range m {
    60  
    61  		if vf, ok := v.(func() interface{}); ok {
    62  			// if it's a DeferredVal, call it.
    63  			m2[k] = vf()
    64  
    65  		} else {
    66  			// else use the value as is.
    67  			m2[k] = v
    68  		}
    69  	}
    70  	return m2
    71  }