ft

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2025 License: 0BSD Imports: 16 Imported by: 0

README

ft – function trace

Go Report Card GoDoc License

A lightweight library for tracing function execution with OpenTelemetry integration, structured logging, and metrics collection.

Why?

In most of my projects, I start by relying on simple logs to get quick insights into the application. As the project evolves, I usually add metrics and traces for improved observability, but setting up all the libraries can be time-consuming. This library allows you to enable the observability of your functions with just two lines of code.

Features

  • Structured logging using slog.
  • OpenTelemetry tracing integration.
  • Metrics for execution counts and duration.
  • Configurable log level.
  • Option to opt out of metrics and tracing.

Usage

Just add two lines to the beginning of the function:

func Do(ctx context.Context) (err error) {
    ctx, span := ft.Start(ctx, "main.Do", ft.WithErr(&err)) // Log when we enter the `Do` function.
    defer span.End()                                        // Log, trace and meter when we exit the `Do` function.

    err = errors.New("unexpected error")
	
    return
}

If you run the code above, you will see the following output:

time=2025-01-25T21:55:27.068+01:00 level=INFO msg="action started" action=main.Do
time=2025-01-25T21:55:27.069+01:00 level=ERROR msg="action ended" action=main.Do duration_ms=0.743 error="unexpected error"

Setup OTEL tracer and meter globally and ft will start sending metrics and traces to the OTLP collector:

mp, _, _ := autometer.NewMeterProvider(context.Background())
otel.SetMeterProvider(mp)
tp, _, _ := autotracer.NewTracerProvider(context.Background())
otel.SetTracerProvider(tp)

ft.SetMetricsEnabled(true)
ft.SetTracingEnabled(true)

[!TIP] In the example above I use go-faster/sdk to setup OTEL based on environment variables.

Configuration

ft package provides many functions to configure its behaviour. See the table below:

Here's a markdown table with all the Set functions and their descriptions:

Function Description
SetDurationMetricUnit(unit string) Sets the global duration metric unit. Accepts either millisecond (ms) or second (s) as valid units. Defaults to millisecond if invalid unit is provided.
SetDefaultLogger(l *slog.Logger) Sets the global logger instance. Does nothing if nil logger is provided.
SetLogLevelOnFailure(level slog.Level) Sets the global log level for failure scenarios.
SetLogLevelOnSuccess(level slog.Level) Sets the global log level for success scenarios.
SetTracingEnabled(v bool) Enables or disables global tracing functionality.
SetMetricsEnabled(v bool) Enables or disables global metrics collection.
SetClock(c clockwork.Clock) Sets the global clock instance used for time-related operations.
SetAppendOtelAttrs(v bool) Enables or disables the appending of OpenTelemetry attributes globally.

Documentation

Index

Constants

View Source
const (

	// DurationMetricUnitSecond represents seconds as the unit for duration metrics.
	DurationMetricUnitSecond = "s"
	// DurationMetricUnitMillisecond represents milliseconds as the unit for duration metrics.
	DurationMetricUnitMillisecond = "ms"
)

Variables

This section is empty.

Functions

func SetAppendOtelAttrs added in v0.2.0

func SetAppendOtelAttrs(v bool)

func SetClock added in v0.2.0

func SetClock(c clockwork.Clock)

func SetDefaultLogger

func SetDefaultLogger(l *slog.Logger)

func SetDurationMetricUnit added in v0.2.0

func SetDurationMetricUnit(unit string)

func SetLogLevelOnFailure added in v0.2.0

func SetLogLevelOnFailure(level slog.Level)

func SetLogLevelOnSuccess added in v0.2.0

func SetLogLevelOnSuccess(level slog.Level)

func SetMetricsEnabled added in v0.2.0

func SetMetricsEnabled(v bool)

func SetTracingEnabled added in v0.2.0

func SetTracingEnabled(v bool)

Types

type Option added in v0.2.0

type Option func(cfg *SpanConfig)

func WithAttrs added in v0.2.0

func WithAttrs(attrs ...slog.Attr) Option

func WithErr added in v0.2.0

func WithErr(err *error) Option

type Span

type Span interface {
	End()
}

Span represents a traced and logged operation that can be ended.

func Start added in v0.2.0

func Start(ctx context.Context, action string, opts ...Option) (context.Context, Span)

Start begins a new traced and logged span for the given action. It returns an updated context and a Span that should be ended when the operation completes.

type SpanConfig added in v0.2.0

type SpanConfig struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL