github.com/brownsys/tracing-framework-go@v0.0.0-20161210174012-0542a62412fe/xtrace/client/log.go (about)

     1  package client
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/brownsys/tracing-framework-go/xtrace/client/internal"
    10  	"github.com/brownsys/tracing-framework-go/xtrace/internal/pubsub"
    11  	"github.com/golang/protobuf/proto"
    12  )
    13  
    14  var client *pubsub.Client
    15  
    16  // Connect initializes a connection to the X-Trace
    17  // server. Connect must be called (and must complete
    18  // successfully) before Log can be called.
    19  func Connect(server string) error {
    20  	var err error
    21  	client, err = pubsub.NewClient(server)
    22  	return err
    23  }
    24  
    25  var topic = []byte("xtrace")
    26  var processName = strings.Join(os.Args, " ")
    27  
    28  // Log logs the given message. Log must not be
    29  // called before Connect has been called successfully.
    30  func Log(str string) {
    31  	if client == nil {
    32  		panic("xtrace/client.Log: no connection to server")
    33  	}
    34  
    35  	parent, event := newEvent()
    36  	var report internal.XTraceReportv4
    37  
    38  	report.TaskId = new(int64)
    39  	*report.TaskId = GetTaskID()
    40  	report.ParentEventId = []int64{parent}
    41  	report.EventId = new(int64)
    42  	*report.EventId = event
    43  	report.Label = new(string)
    44  	*report.Label = str
    45  
    46  	report.Timestamp = new(int64)
    47  	*report.Timestamp = time.Now().UnixNano() / 1000 // milliseconds
    48  
    49  	report.ProcessId = new(int32)
    50  	*report.ProcessId = int32(os.Getpid())
    51  	report.ProcessName = new(string)
    52  	*report.ProcessName = processName
    53  	host, err := os.Hostname()
    54  	if err != nil {
    55  		report.Host = new(string)
    56  		*report.Host = host
    57  	}
    58  
    59  	buf, err := proto.Marshal(&report)
    60  	if err != nil {
    61  		panic(fmt.Errorf("internal error: %v", err))
    62  	}
    63  
    64  	// NOTE(joshlf): Currently, Log blocks until the log message
    65  	// has been written to the TCP connection to the X-Trace server.
    66  	// This makes testing easier, but ideally we should optimize
    67  	// so that the program can block before it quits, but each
    68  	// call to Log is not blocking.
    69  	client.PublishBlock(topic, buf)
    70  }