A Simple Tracing Framework for Go

By Jochen Voss, last updated 2013-07-16

The trace package provides a simple tracing framework for the excellent Go programming language. Code using this framework can emit diagnostic messages using the trace.T() function. In normal operation, calls to trace.T() have no effect and are very fast. When tracing is enabled, in order to track down a problem or to explore the inner workings of a program, listeners can be attached to record and display all trace messages.

Main features:

Download

To download the trace package, simply use the go get command as follows:

go get github.com/seehuhn/trace

The source code is available at github.com/seehuhn/trace.

Usage

Detailed usage instructions are available via the package's online help, either on godoc.org or on the command line:

go doc github.com/seehuhn/trace

A short summary can be found below.

Sending Messages

trace.T("a/b/c", trace.PrioError,
	"failed to connect to server %q, using offline mode", serverName)

The first argument in this call is a path which gives information about the origin of the message, the second argument indicates the importance of the message. Both, the path and the priority are used to decide which listeners receive the correponding message. The following arguments, a format string and additional optional arguments, are passed to fmt.Sprintf to compose the message reported to the listeners registered for the given message path.

Receiving Messages

Listeners can subscribe to messages, either for a given path or for all paths, using the Register() method. A minimum priority for messages to be delivered can be used. Example:

func MyListener(t time.Time, path string, prio Priority, msg string) {
    log.Println(msg)
}

func main() {
    listener := trace.Register(MyListener, "a/b", trace.PrioAll)
    // ... code which calls trace.T()
    listener.Unregister()
}

This code installs MyListener as a handler which receives all messages sent for the path "a/b" and its sub-paths.

Copyright © 2013 Jochen Voss. All content on this website (including text, pictures, and any other original works), unless otherwise noted, is licensed under the CC BY-SA 4.0 license.