package main
import (
"context"
"github.com/gaylatea/instrument"
)
func main() {
ctx := context.Background()
instrument.Infof(ctx, "Hello!")
}
// Emits a log line:
// {"meta.instance": "018feac5-27db-7dcb-bcaf-483155a5ea06", "meta.timestamp": "2024-06-05T23:39:00Z", "meta.level": "INF", "meta.caller": "main.main", "meta.file": "/Users/gaylatea/src/instrument/example/main.go", "meta.line": 77, "log.message": "Hello!"}
instrument
uses tags to contextualize events, allowing you to trace the path of a log. To add tags, use:
newCtx := instrument.With(ctx, "tag.new", true)
newCtx := instrument.WithAll(ctx, instrument.Tags{
"key": "value",
"another": time.Now(),
})
To emit a log line with levels, use:
instrument.Tracef(ctx, "Trace text")
instrument.Debugf(ctx, "Debug text")
instrument.Infof(ctx, "Info text")
instrument.Warnf(ctx, "Warning text")
instrument.Errorf(ctx, "Error text")
To force exit the program with a log line, you can use:
instrument.Fatalf(ctx, "This should stop the program.")
All the preceding logs support fmt.Sprintf
formatting.
instrument
suppresses Debugf
or Tracef
logs by default. To turn them on:
instrument.SetDebug(true)
instrument.SetTrace(true) // implies SetDebug(true)
Tracing wraps a block of code with timing and call stack information. To start a trace:
if err := instrument.WithSpan(ctx, "Name", func(ctx context.Context, addToParent func(instrument.Tags)) error {
// Your code here.
}); err != nil {
// Use the returned error.
}
The provided addToParent
function adds tags to the created span from your code.
To emit an event without the tracing or logging metadata:
instrument.PostEvent(ctx, "Name", instrument.Tags{
"something": "you need",
})
Unlike logs and traces, raw events don't contain tags from the provided context.
instrument
uses a default terminal sink to emit newline-delimited JSON to stderr
, with optional colors in a TTY.
You can turn the default sink off with:
instrument.Silence(true)
To add a sink, implement the instrument.Sink
interface.
To set a sink for all events:
instrument.UseSink(yourSink)
To set a sink for a context and its descendants:
newCtx := instrument.WithSink(ctx, yourSink)
A sample program with all available features: example/main.go
instrument
is dedicated to the public domain. See the CC0-1.0 License for details.