go-instrument

⚡️ Automatically add Trace Spans to Go functions

https://github.com/nikolaydubina/go-instrument

Science Score: 44.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (11.0%) to scientific vocabulary

Keywords

ast auto-instrumentation datadog go golang instrumentation monitoring newrelic opentelemetry tooling

Keywords from Contributors

generic interactive mesh interpretability profiles benchmarking sequences projection optim embedded
Last synced: 6 months ago · JSON representation ·

Repository

⚡️ Automatically add Trace Spans to Go functions

Basic Info
  • Host: GitHub
  • Owner: nikolaydubina
  • License: mit
  • Language: Go
  • Default Branch: master
  • Homepage:
  • Size: 4.02 MB
Statistics
  • Stars: 272
  • Watchers: 4
  • Forks: 9
  • Open Issues: 2
  • Releases: 27
Topics
ast auto-instrumentation datadog go golang instrumentation monitoring newrelic opentelemetry tooling
Created over 3 years ago · Last pushed 7 months ago
Metadata Files
Readme Funding License Citation Codeowners Security

README.md

⚡️ go-instrument

codecov Go Report Card Go Reference Mentioned in Awesome Go go-recipes OpenSSF Scorecard Hits

Automatically add Trace Spans to Go functions

bash go install github.com/nikolaydubina/go-instrument@latest

bash find . -name "*.go" | xargs -I{} go-instrument -app my-service -w -filename {}

Functions with context.Context in arguments go func (s Cat) Name(ctx context.Context) (name string, err error) { ...

will be instrumented with span go func (s Cat) Name(ctx context.Context) (name string, err error) { ctx, span := otel.Trace("my-service").Start(ctx, "Cat.Name") defer span.End() defer func() { if err != nil { span.SetStatus(codes.Error, "error") span.RecordError(err) } }() ...

Example HTTP server go-instrument-example as it appears in Datadog.

This tool uses standard Go library to modify AST with instrumentation. You can add new instrumentations by defining your own Instrumenter and invoking Processor like it is done in main.

Motivation

It is laborious to add tracing code to every function manually. The code repeats 99% of time. Other languages can either modify code or have wrapper notations that makes even manual tracing much less laborious.

As of 2025-05-11, official Go does not support automatic function traces^2.

Is there a way to automatically intercept each function call and create traces?

Go doesn’t provide a way to automatically intercept every function call and create trace spans. You need to manually instrument your code to create, end, and annotate spans.

Thus, providing automated version to add Trace Spans annotation.

Performance

Go Compiler Inlining

Since we are adding multiple functions calls, it affects Go compiler decisions on inlining. It is expected that Go will less likely inline.

For example, can inline function bash $ go build -gcflags="-m -m" ./internal/testdata 2>&1 | grep OneLine internal/testdata/basic.go:80:6: can inline OneLineTypical with cost 62 as: func(context.Context, int) (int, error) { return fib(n), nil }

bash go-instrument -w -filename internal/testdata/basic.go

Can not inline after instrumentation bash $ go build -gcflags="-m -m" ./internal/testdata 2>&1 | grep OneLine internal/testdata/basic.go:132:6: cannot inline OneLineTypical: unhandled op DEFER

Appendix A: Related Work

  • https://github.com/hedhyw/otelinji — Very similar to current project. This tool gracefully handles code comments, so that its output can be tracked with normal code in version control. Main difference current project focuses on minimal code and dependencies.
  • https://github.com/open-telemetry/opentelemetry-go-instrumentation — (in development) official eBPF based Go auto instrumentation
  • https://github.com/keyval-dev/opentelemetry-go-instrumentation — eBPF based Go auto instrumentation of pre-selected libraries
  • https://developers.mattermost.com/blog/instrumenting-go-code-via-ast — Very similar. Instrumenting Go code for tracing.
  • https://github.com/gobwas/gtrace — non-OTEL, custom tracing framework that uses code generation

Appendix B: Other Languages

Java

Java runtime modifies bytecode of methods on load time that adds instrumentation calls. Pre-defined libraries are instrumented (http, mysql, etc).

✅ Very short single line decorator statement can be used to trace selected methods.

Datadog ```java import datadog.trace.api.Trace

public class BackupLedger { @Trace public void write(List transactions) { for (Transaction transaction : transactions) { ledger.put(transaction.getId(), transaction); } } } ```

OpenTelemetry ```java import io.opentelemetry.instrumentation.annotations.WithSpan;

public class MyClass { @WithSpan public void myMethod() { <...> } } ```

✅ Automatic instrumentation of all functions is also possible.

Datadog supports wildcard for list of methods to trace.

dd.trace.methods
Environment Variable: DDTRACEMETHODS
Default: null
Example: package.ClassName[method1,method2,...];AnonymousClass$1[call];package.ClassName[]
List of class/interface and methods to trace. Similar to adding @Trace, but without changing code. Note: The wildcard method support ([
]) does not accommodate constructors, getters, setters, synthetic, toString, equals, hashcode, or finalizer method calls

bash java -javaagent:/path/to/dd-java-agent.jar -Ddd.service=web-app -Ddd.env=dev -Ddd.trace.methods="*" -jar path/to/application.jar

Python

Python monkeypatching of functions at runtime is used to add instrumentation calls. Pre-defined libraries are instrumented (http, mysql, etc).

✅ Very short single line decorator statement can be used to trace selected methods.

Datadog ```python from ddtrace import tracer

class BackupLedger: @tracer.wrap() def write(self, transactions): for transaction in transactions: self.ledger[transaction.id] = transaction ```

OpenTelemetry python @tracer.start_as_current_span("do_work") def do_work(): print("doing some work...")

⚠️ Automatic instrumentation of all functions is also possible via monkeypatching (fidning stable library is pending).

C++

❌ Only manual instrumentation.

Rust

✅ Very short single line decorator statement can be used to trace selected functions with well-establisehd tokio framework.

```rust

[tracing::instrument]

pub fn shave(yak: usize) -> Result<(), Box> { ```

```rust

[instrument]

async fn write(stream: &mut TcpStream) -> io::Result { ```

  • https://github.com/tokio-rs/tracing
  • https://opentelemetry.io/docs/instrumentation/rust
  • https://docs.rs/opentelemetry/latest/opentelemetry
  • https://github.com/open-telemetry/opentelemetry-rust/tree/main/examples
  • https://docs.rs/datadog-apm/latest/datadog_apm

Appendix C: Generating Many Spans

1.97K spans, fibbonaci

3.7K spans, go cover treemap

ADR

  • 2025-05-11 not using commands like //instrument:exclude because: in practice this tool is used to instrument everything; there is still mechanism to exclude whole file; there is already automatic detection of instrumented functions. therefore, to simplify not using commands.
  • not using eBPF because: with eBPF we can track latency, but we would not be able to assign errors to spans; some platforms may not have access to eBPF;
  • not wrapping internal functions. benefit of wrapping is to keep original code without modifications. however, manual step for switching would still be requied. given every single function is duplciated and is within same package, code will quickly become messy and hard to maintain by user.
  • not wrapping exported functions. typically, packages are failry big and performs lots of logic. oftencase, business domains are split only in few large packages. low level packages are already likely to be traced with standard tracing (MySQL, het/http, etc). thus, it is doubtful how much benefit would be from tracing only exported functions and only on import
  • not wrapping exported functions with separate package, because this would lead to circular dependency failure, since some even exported functions in original package may be called withing same package. thus, we would either skip those calls, or fail with circular dependency while trying to wrap those.

Owner

  • Name: Nikolay Dubina
  • Login: nikolaydubina
  • Kind: user

Citation (CITATION.cff)

cff-version: 1.2.0
message: If you reference this library in publication, please cite it as below.
title: Automatic Go Instrumentation
abstract: Automatic Go Instrumentation by modifying AST
authors:
- family-names: Dubina
  given-names: Nikolay
version: 2.1
date-released: 2022-11-10
license: MIT
repository-code: https://github.com/nikolaydubina/go-instrument
url: https://github.com/nikolaydubina/go-instrument

GitHub Events

Total
  • Create event: 21
  • Release event: 13
  • Issues event: 11
  • Watch event: 60
  • Delete event: 9
  • Issue comment event: 18
  • Push event: 44
  • Pull request review comment event: 29
  • Pull request review event: 23
  • Pull request event: 24
  • Fork event: 2
Last Year
  • Create event: 21
  • Release event: 13
  • Issues event: 11
  • Watch event: 60
  • Delete event: 9
  • Issue comment event: 18
  • Push event: 44
  • Pull request review comment event: 29
  • Pull request review event: 23
  • Pull request event: 24
  • Fork event: 2

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 135
  • Total Committers: 6
  • Avg Commits per committer: 22.5
  • Development Distribution Score (DDS): 0.133
Past Year
  • Commits: 39
  • Committers: 4
  • Avg Commits per committer: 9.75
  • Development Distribution Score (DDS): 0.282
Top Committers
Name Email Commits
Nikolay Dubina n****b@g****m 117
dependabot[bot] 4****] 12
Mateusz Czubak m****z@f****o 3
John Fallis 2****s 1
Avicienna Ulhaq a****q@g****m 1
Andrey Burov b****6@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 16
  • Total pull requests: 44
  • Average time to close issues: 4 months
  • Average time to close pull requests: 5 days
  • Total issue authors: 4
  • Total pull request authors: 7
  • Average comments per issue: 1.38
  • Average comments per pull request: 1.07
  • Merged pull requests: 40
  • Bot issues: 0
  • Bot pull requests: 15
Past Year
  • Issues: 7
  • Pull requests: 20
  • Average time to close issues: 29 days
  • Average time to close pull requests: 10 days
  • Issue authors: 1
  • Pull request authors: 4
  • Average comments per issue: 0.29
  • Average comments per pull request: 1.4
  • Merged pull requests: 17
  • Bot issues: 0
  • Bot pull requests: 10
Top Authors
Issue Authors
  • nikolaydubina (11)
  • leonklingele (3)
  • matino (2)
  • dependabot[bot] (1)
  • davidjwilkins (1)
Pull Request Authors
  • nikolaydubina (30)
  • dependabot[bot] (22)
  • matino (6)
  • noxymon (3)
  • burik666 (2)
  • jfallis (2)
Top Labels
Issue Labels
bug (5) dependencies (1) enhancement (1)
Pull Request Labels
dependencies (22)

Packages

  • Total packages: 1
  • Total downloads: unknown
  • Total dependent packages: 0
  • Total dependent repositories: 0
  • Total versions: 30
proxy.golang.org: github.com/nikolaydubina/go-instrument
  • Versions: 30
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 7.0%
Average: 8.2%
Dependent repos count: 9.3%
Last synced: 6 months ago

Dependencies

.github/workflows/tests.yml actions
  • actions/checkout v2 composite
  • actions/setup-go v2 composite
  • codecov/codecov-action v2 composite
go.mod go
  • golang.org/x/tools v0.3.0
go.sum go
  • golang.org/x/sys v0.2.0
  • golang.org/x/tools v0.3.0