🧶 Dead simple, lightweight tracing.

Overview

🧶 tracer

Dead simple, lightweight tracing.

Build Documentation Quality Template Coverage Awesome

💡 Idea

The tracer provides API to trace execution flow.

func Do(ctx context.Context) {
	defer tracer.Fetch(ctx).Start().Stop()

	// do some heavy job
}

A full description of the idea is available here.

🏆 Motivation

At Avito, we use the Jaeger - a distributed tracing platform. It is handy in most cases, but at production, we also use sampling. So, what is a problem, you say?

I had 0.02% requests with a write: broken pipe error and it was difficult to find the appropriate one in the Sentry which also has trace related to it in the Jaeger.

For that reason, I wrote the simple solution to handle this specific case and found the bottleneck in our code quickly.

🤼‍♂️ How to

import (
	"context"
	"io"
	"net/http"
	"time"

	"github.com/kamilsk/tracer"
)

func InjectTracer(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		req = req.WithContext(tracer.Inject(req.Context(), make([]*tracer.Call, 0, 10)))
		handler.ServeHTTP(rw, req)
	})
}

func Handle(rw http.ResponseWriter, req *http.Request) {
	ctx, cancel := context.WithTimeout(req.Context(), time.Second)
	defer cancel()

	call := tracer.Fetch(req.Context()).Start(req.Header.Get("X-Request-Id"))
	defer call.Stop()

	...

	call.Checkpoint("serialize")
	data, err := FetchData(ctx, req.Body)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	call.Checkpoint("store")
	if err := StoreIntoDatabase(ctx, data); err != nil {
		http.Error(rw,
			http.StatusText(http.StatusInternalServerError),
			http.StatusInternalServerError)
		return
	}
	rw.WriteHeader(http.StatusOK)
}

func FetchData(ctx context.Context, r io.Reader) (Data, error) {
	defer tracer.Fetch(ctx).Start().Stop()

	// fetch a data into a struct
}

func StoreIntoDatabase(ctx context.Context, data Data) error {
	defer tracer.Fetch(ctx).Start().Stop()

	// store the data into a database
}

Output:

allocates at call stack: 0, detailed call stack:
	call Handle [ca7a87c4-58d0-4fdf-857c-ef49fc3bf271]: 14.038083ms, allocates: 2
		checkpoint [serialize]: 1.163587ms
		checkpoint [store]: 2.436265ms
	call FetchData: 1.192829ms, allocates: 0
	call StoreIntoDatabase: 10.428663ms, allocates: 0

🧩 Integration

The library uses SemVer for versioning, and it is not BC-safe through major releases. You can use go modules to manage its version.

$ go get github.com/kamilsk/[email protected]

made with ❤️ for everyone

You might also like...
Dead simple rate limit middleware for Go.

Limiter Dead simple rate limit middleware for Go. Simple API "Store" approach for backend Redis support (but not tied too) Middlewares: HTTP, FastHTTP

A dead simple, no frills Go cross compile tool

Gox - Simple Go Cross Compilation Gox is a simple, no-frills tool for Go cross compilation that behaves a lot like standard go build. Gox will paralle

Dead simple rate limit middleware for Go.

Limiter Dead simple rate limit middleware for Go. Simple API "Store" approach for backend Redis support (but not tied too) Middlewares: HTTP, FastHTTP

Task Timer (tt) is a dead simple TUI task timer
Task Timer (tt) is a dead simple TUI task timer

tasktimer Task Timer (tt) is a dead simple TUI task timer Usage To get started, just run tt: tt You'll be presented with something like this: You can

A dead simple Go library for sending notifications to various messaging services.
A dead simple Go library for sending notifications to various messaging services.

A dead simple Go library for sending notifications to various messaging services. About Notify arose from my own need for one of my api server running

A dead simple parser package for Go
A dead simple parser package for Go

A dead simple parser package for Go

A dead simple tool to sign files and verify digital signatures.

minisign minisign is a dead simple tool to sign files and verify signatures. $ minisign -G

Dead simple reverse proxy for all your containerized needss
Dead simple reverse proxy for all your containerized needss

Whats this ? Pawxi is yet another reverse proxy designed with simplicity in mind. Born out of a certain users frustration at the complexity of setting

DSF - Dead Simple Fileserver

A dead simple HTTP fileserver to share your files across LAN.

A dead simple tool to rename your files for smooth web access!

ffw - Friendly Files for the Web Easily rename files from a folder to be compatible with the web Run ffw and that's it! Installation on macOs brew tap

🪵 A dead simple, pretty, and feature-rich logger for golang
🪵 A dead simple, pretty, and feature-rich logger for golang

🪵 lumber 🪵 A dead simple, pretty, and feature-rich logger for golang 🚀 Install 🌲 Logging Functions lumber.Success() lumber.Info() lumber.Debug() l

A dead simple, stupid, http service.

A dead simple, stupid, http service implemented in a complicated way just for the sake of following Go design patterns and scalability. Useful for learning and testing basic kubernetes networking. Made on an insomniac night.

⚙️ Dead Simple Config Management, load and persist config without having to think about where and how.

Configo Dead Simple Config Management, load and persist config without having to think about where and how. Install go get github.com/UltiRequiem/conf

A dead simple cli utility to help you manage your git stash
A dead simple cli utility to help you manage your git stash

A dead simple cli utility to help you manage your git stash.

A dead simple CLI tool that prints the next semantic version based on the last tag of your git repository

nextver A dead simple CLI tool that prints the next semantic version based on the last tag of your git repository. Install go install github.com/junk1

A dead simple Go wrapper around the hidden moonarch.app API.

moonarch A dead simple Go wrapper around the hidden moonarch.app API. How-To First, get the repository: go get github.com/lazdotdigital/moonarch. moon

A dead simple parser package for Go
A dead simple parser package for Go

A dead simple parser package for Go V2 Introduction Tutorial Tag syntax Overview Grammar syntax Capturing Capturing boolean value Streaming Lexing Sta

Tcp-proxy - A dead simple reverse proxy server.

tcp-proxy A proxy that forwords from a host to another. Building go build -ldflags="-X 'main.Version=$(git describe --tags $(git rev-list --tags --max

Error tracing and annotation.

errors -- import "github.com/juju/errgo" The errors package provides a way to create and diagnose errors. It is compatible with the usual Go error idi

Comments
  • reduce allocations

    reduce allocations

    master

    BenchmarkTracing/silent-12         	  200000	      7755 ns/op	    1816 B/op	      24 allocs/op
    BenchmarkTracing/full-12           	  200000	      8880 ns/op	    3944 B/op	      45 allocs/op
    
    type:refactoring 
    opened by kamilsk 3
  • add possibility to preallocate checkpoints

    add possibility to preallocate checkpoints

    call := tracer.Fetch(ctx).With(make([]Checkpoint, 0, 10)).Start()
    defer call.Stop()
    ...
    call.Checkpoint()
    ...
    call.Checkpoint("id", "labelX", "labelY")
    ...
    
    type:feature status:pending 
    opened by kamilsk 0
  • example with sla

    example with sla

    func Middleware(handler http.Handler) http.Handler {
      return http.HandlerFunc(func (...) {
        ctx := context.WithValue(req.Context(), key, tracer)
        http.ServeHTTP(rw, req.WithContex(ctx))
        if ctx.Err() != nil {
          // fetch tracer, write trace into Sentry
        }
      })
    }
    
    type:docs status:pending 
    opened by kamilsk 0
Owner
Kamil Samigullin
Software engineer.
Kamil Samigullin
Simple profiling for Go

profile Simple profiling support package for Go installation go get github.com/pkg/profile usage Enabling profiling in your application is as simple

null 1.8k Jan 1, 2023
A simple Go library for 3D ray-tracing rendering, implementing the book Ray Tracing in One Weekend.

Ray Tracing in Go A Go implementation of the book Ray Tracing in One Weekend. The repository provides a library to describe and render your own scenes

Yuto Takahashi 53 Sep 23, 2022
Lightweight and dead-simple CI detection.

is-ci Lightweight and dead-simple CI detection for golang. This mod is based on the @npmcli/ci-detect package. Install go get -u github.com/wesleimp/i

Weslei Juan Novaes Pereira 4 Dec 17, 2021
bf.go - A dead simple brainfuck interpreter Slow and simple

bf.go - A dead simple brainfuck interpreter Slow and simple. Can execute pretty much all tested Brainfuck scripts. Installation If you have Go install

Chris 0 Oct 15, 2021
Golog is a logger which support tracing and other custom behaviors out of the box. Blazing fast and simple to use.

GOLOG Golog is an opinionated Go logger with simple APIs and configurable behavior. Why another logger? Golog is designed to address mainly two issues

Damiano Petrungaro 37 Oct 2, 2022
A dead simple, highly performant, highly customizable sessions middleware for go http servers.

If you're interested in jwt's, see my jwt library! Sessions A dead simple, highly performant, highly customizable sessions service for go http servers

Adam Hanna 70 Dec 19, 2022
A dead simple configuration manager for Go applications

Store Store is a dead simple configuration manager for Go applications. I didn't like existing configuration management solutions like globalconf, tac

Ian P Badtrousers 265 Dec 24, 2022
Dead simple Go database migration library.

migrator Dead simple Go database migration library. Features Simple code Usage as a library, embeddable and extensible on your behalf Support of any d

David Lobe 135 Nov 9, 2022
A dead simple 2D game library for Go

Ebiten (v2) A dead simple 2D game library for Go Ebiten is an open source game library for the Go programming language. Ebiten's simple API allows you

Hajime Hoshi 7.6k Dec 28, 2022
Dead simple, super fast, zero allocation and modular logger for Golang

Onelog Onelog is a dead simple but very efficient JSON logger. It is one of the fastest JSON logger out there. Also, it is one of the logger with the

Francois Parquet 402 Sep 26, 2022