Instrumentation is Easy in Golang

Tony Montemuro
November 29th, 2026
Featured image for Instrumentation is Easy in Golang

In many other programming languages, intrumenting your code is non-trivial. For example, in C, one way to instrument your code is through LLVM, which requires:

  • Getting a very basic understaning of LLVM
  • Learning the basics of LLVM IR, a Static Single Assignment (SSA) assembly language
  • Getting used to converting your C code to LLVM IR
  • Getting a very basic understanding of C++
  • Write the LLVM pass in C++ that instruments your LLVM IR
  • Getting used to running compiler passes on your IR, and compiling the instrumented IR to machine code

Not only do you have to learn a third-party library (a very advanced one at that), but you also have to use an entirely separate programming language to perform the instrumentation!

As an aside, a good reason to learn the above LLVM approach is because it works with many different languages, as long as the language can be compiled down to LLVM IR. So you could actually use this method to instrument Go code.

That’s a lot of prerequisite material to learn in order to instrument the code. Is instrumenting Go code as painful? Thankfully, it’s not! In the world of Go, where simplicity is valued, and batteries are included in the standard library, we can instrument Go code, simply, using nothing but the standard library. In this article, I will prove that getting started with instrumenting your Go code is easy!

Getting started

Before we jump in, we need a program to instrument! This article will instrument the following Go code:

package main

import (
	"fmt"
	"os"
	"strconv"
)

// toBadArgErr returns an error for a mistyped arg.
func toBadArgErr(arg string, n int) error {
	return fmt.Errorf("invalid arg %d: %s, int expected", n, arg)
}

// parseArgs parses the CLI args.
func parseArgs() (int, int, error) {
	var n1, n2 int
	args := os.Args[1:]
	n := len(args)
	if n < 2 {
		return n1, n2, fmt.Errorf("expected 2 int args: got %d args", n)
	}

	n1, err := strconv.Atoi(args[0])
	if err != nil {
		return n1, n2, toBadArgErr(args[0], n)
	}

	n2, err = strconv.Atoi(args[1])
	if err != nil {
		return n1, n2, toBadArgErr(args[1], n)
	}

	return n1, n2, nil
}

func main() {
	// read input args
	n1, n2, err := parseArgs()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// compute sum of args
	//
	// there is a bug in this program: when the sum is a multiple of
	// 150, the program fails with a nil pointer dereference error.
	//
	// we could use instrumentation, combined with software analysis
	// techniques, to find this bug (and similar, less trivial bugs)
	sum := n1 + n2
	ptr := &sum
	if sum%2 == 0 {
		if sum%3 == 0 {
			if sum%25 == 0 {
				ptr = nil
			}
		}
	}

	fmt.Println(*ptr)
}

In this program, there is a purposeful bug. An idea for debugging this program is to use a fuzzing technique, which starts by feeding the program random inputs, and adjusting the inputs based on the number of encountered conditional statements. In this example, more conditional statements encountered is a proxy for more interesting runs of the program.

Disclaimer: Number of conditional statements encountered is not a general technique for determining whether or not an input is “interesting”. How you determine an interesting input will often depend on your use case.

To achieve this, we first need a way to keep track of the conditionals we hit during execution. This can be done via instrumentation! This article will aim to achieve this kind of instrumentation, but the basic techniques described in this article can be extended to achieve all kinds of program instrumentation.

If you are following along, create a main.go at the root of your project repository, and paste the above contents into your newly created file.

Parsing your Go code

Before we can start discovering those juicy insights via analysis techniques fed by our clever instrumentation, we first need to read our program and represent it as an abstract syntax tree (AST).

To do this, we can refer to go/parser, a standard library package that gives us the ability to parse Go source code. In particular, let’s focus on the ParseFile function. We can start by looking at the function signature from the docs:

func ParseFile(fset *token.FileSet, filename string, src any, mode Mode) (f *ast.File, err error)

This function takes 4 inputs. Here’s how to understand each one:

  1. fset *token.FileSet: A pointer to a FileSet type, defined in the go/token standard library package. You can think of this as a container that holds onto a set of Go source files. It’s used by the parser to interact with the source file we are instrumenting. For the sake of this tutorial, we can simply pass in a fresh *token.FileSet, by passing in the result of token.NewFileSet().
  2. filename: The name of the file we want to instrument. This argument is used either to:
    1. Read the file from disk as source code
    2. Used only as an identifier of the code when recording position information
  3. src: When set to nil, we read the file from disk as source code (1). Otherwise, can pass in one of string, []byte, or io.Reader, and read the file from this source. In this case, the filename argument is used only as an identifier (2). For the article, we are just going to read the file from disk, so we will pass in nil for this argument.
  4. mode: A valid parser.Mode value, which controls aspects of how the source code is parsed. For the sake of simplicity, we will just pass the one recommended flag as the argument: parser.SkipObjectResolution.

You can think of each mode as a boolean flag. Therefore, you have the ability to pass in multiple flags using bitwise OR (|) operator. For example: ParseComments|SkipObjectResolution.

This function returns 2 outputs. Here’s how to understand each one:

  1. f *ast.File: A pointer to a File type, defined in the go/ast standard library package. If there’s an error during parsing, this is returned as nil. Otherwise, we get back an AST node representing our go source file. From this value, we have what we need to begin instrumentation.
  2. err error: If there’s an error during parsing, we get back a concrete error. Otherwise, nil is returned.

With an understanding of this function, we have enough to at least get started. Let’s create our file at cmd/instrumentation/main.go:

package main

import (
	"fmt"
	"go/parser"
	"go/token"
	"io"
	"os"
)

// printUsage prints usage information to w.
func printUsage(w io.Writer) {
	fmt.Fprintln(w, "\nusage: ./cmd/instrument/main [filepath]\nfilepath: A filepath to Go source code you wish to instrument.\n")
}

func main() {
	// read filename as cli arg
	args := os.Args[1:]
	if len(args) == 0 {
		printUsage(os.Stderr)
		os.Exit(1)
	}
	filename := args[0]

	// parse file
	f, err := parser.ParseFile(token.NewFileSet(), filename, nil, parser.SkipObjectResolution)
	if err != nil {
		fmt.Fprintf(os.Stderr, "problem parsing source file: %s", err.Error())
		os.Exit(1)
	}

	// if we made it this far, we successfully parsed our source file
	// print out list of imports to demonstrate parsing was a success
	fmt.Printf("successfully parsed source file %s! imports:\n", filename)
	for _, i := range f.Imports {
		fmt.Printf("\t- %s\n", i.Path.Value)
	}
}

This code will attempt to read a source file specified by a command-line argument. If parsing is successful, we have a little demo of something we can do with our AST node: printing out all the imports in our source file.

Let’s try this out! Compile and run this instrumentation tool:

go build -o ./cmd/instrument/main ./cmd/instrument/main.go
./cmd/instrument/main main.go

The output of the above should be a list of imports in your source code. For example:

successfully parsed source file main.go! imports:
        - "fmt"
        - "os"
        - "strconv"

Traversing over the AST

Now that we have our AST, how can we start to interact with it? In the previous section, we iterate over the imports, but this is just a tiny slice of a typical program.

To instrument our program, we need to be able to traverse the syntax tree, so we can visit each node in the tree, and perform our instrumentation where necessary. Luckily, the go/ast standard library package provides multiple functions to traverse the tree. To keep things simple, we will focus on the most basic of all the available functions.

Preorder provides us with an iterator we can use to iterate over all nodes in our syntax tree. In particular, the traversal is performed using depth-first search in preorder.

Preorder traversal

Source: https://commons.wikimedia.org/wiki/File:Preorder-traversal.gif

Because this function returns an iterator, we can, of course, iterate over it using a Range Clause:

for n := range ast.Preorder(f) {
    // process each node here
}

The logistics of how to process each node is where things get a bit tricky. To start, let’s look at the function signature for Preorder:

func Preorder(root Node) iter.Seq[Node]

As you can see, the iterator is a sequence of Node types, which should be somewhat intuitive. But a Node is just an interface:

type Node interface {
	Pos() token.Pos // position of first character belonging to the node
	End() token.Pos // position of first character immediately after the node
}

As long as a concrete type defines these two methods, it can be considered a Node. Therefore, in order to actually do any work (since the two available methods aren’t that useful on their own), we need to perform a type assertion to interact with each Nodes underlying concrete value.

Unsurprisingly, if we dig into the go/ast Types section, we can a lot of exported types, many of which implement the Node interface. If you wanted to build a complete parser, it would be useful to define a type switch, where each case routes to some different processing function. But if your instrumentation is relatively simple, you many only need to attempt a few type assertions per iteration.

The following is a simple example of utilizing the Preorder function to perform some basic processing of the AST:

package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"io"
	"os"
)

// printUsage prints usage information to w.
func printUsage(w io.Writer) {
	fmt.Fprintln(w, "\nusage: ./cmd/instrument/main [filepath]\nfilepath: A filepath to Go source code you wish to instrument.\n")
}

// exprToString returns a string representation of expression e.
func exprToString(e ast.Expr) string {
	switch val := e.(type) {
	case *ast.Ident:
		return val.Name
	case *ast.BinaryExpr:
		return binExprToString(val)
	case *ast.BasicLit:
		return val.Value
	default:
		return "unsupported expression"
	}
}

// binExprToString returns a string representation of binary expression be.
func binExprToString(be *ast.BinaryExpr) string {
	return fmt.Sprintf("%s %s %s", exprToString(be.X), be.Op, exprToString(be.Y))
}

func main() {
	// read filename as cli arg
	args := os.Args[1:]
	if len(args) == 0 {
		printUsage(os.Stderr)
		os.Exit(1)
	}
	filename := args[0]

	// parse file
	f, err := parser.ParseFile(token.NewFileSet(), filename, nil, parser.SkipObjectResolution)
	if err != nil {
		fmt.Fprintf(os.Stderr, "problem parsing source file: %s", err.Error())
		os.Exit(1)
	}

    // print if-statement conditions
    fmt.Printf("successfully parsed source file %s! if-statement conditions:\n", filename)
	for n := range ast.Preorder(f) {
		ifStmt, ok := n.(*ast.IfStmt)
		if !ok {
			continue
		}

		if binExpr, ok := ifStmt.Cond.(*ast.BinaryExpr); ok {
			fmt.Printf("Binary expression: %s\n", binExprToString(binExpr))
		}
	}
}

In this program, we use Preorder to print out a string representing each if-statement conditional in the program.

It’s important to know that this simple example does not generalize to printing out all if-statements conditionals. For starters, we only concern ourselves with binary expressions (our example program only has binary expression conditionals). Also, for each operand (expression) in the binary expression, we only concern ourselves with a tiny subset of the possible expressions. See “exprToString” for what I mean. As you can see, when we attempt to “stringify” the expression, we only attempt for identifiers, binary expressions, or basic literals. Any other type, and we return “unsupported expression”. If we wanted a more generalizable example, we would need to process non-binary conditionals, and extend the type switch.

If you are following along, replace the contents of cmd/instrument/main.go with the above. Re-run the compilation and run steps from earlier:

go build -o ./cmd/instrument/main ./cmd/instrument/main.go
./cmd/instrument/main main.go

If all went well, you should see the following output:

successfully parsed source file main.go! if-statement conditions:
Binary expression: n < 2
Binary expression: err != nil
Binary expression: err != nil
Binary expression: err != nil
Binary expression: sum % 2 == 0
Binary expression: sum % 3 == 0
Binary expression: sum % 25 == 0

Pretty neat, huh? :)

Before we move onto the next section, I want to mention some of the drawbacks of using Preorder for AST traversal:

  • Preorder lacks the ability to prune the AST
  • Preorder lacks the ability to skip subtrees
  • Preorder lacks the ability to perform a different kind of traversal (obviously)

Some instrumentation efforts may require more advanced tree-traversal methods. I suggest checking out Inspect or Walk from go/ast if more advanced traversal is needed.

Instrumenting the AST

Now that we have parsed our source code as an AST, and know how to traverse it, we finally have the ability to start instrumenting our code.

Let’s start by thinking of the algorithm at a high-level:

  1. Parse the source file from disk.
  2. Iterate over the AST, and perform the necessary instrumentation operations.
  3. Write the instrumented source back to disk.

Step 1 is clear: we are able to use the ParseFile function we discussed earlier, defined in go/parser.

There is one catch: unlike before, we will be adding the ParseComments mode to the mode argument of ParseFile. This will ensure our line numbers are accurate.

The traversal part of step 2 is clear (use Preorder from go/ast), but we need to discuss how to perform the instrumentation operations. As it turns out, there are multiple ways to instrument our AST, but for now I will focus on one way: updating the List attribute of the ast/BlockStmt type. In Go, most source code is contained within blocks, also known as a list of statements within braces.

// example of a block: body of a for loop
for i := 1; i <= 10; i++ {
    fmt.Println("incrementing sum by i...") // statement
    sum += i // statement
}

As we traverse our AST, we can perform instrumentation whenever we encounter an ast/BlockStmt, using a type assertion. For each block we encounter, we can add new instances of ast/Stmt to the List slice, based on whatever instrumentation logic we choose:

if block, ok := n.(*ast.BlockStmt); ok {
    // perform instrumentation here: add elements to `block.List`
}

This allows us to add lines of code to our tree! In our example, we want to add a line of code prior to each if-statement, logging the statement’s line and column number. We can then use the logs of each run of the program to help our fuzzing algorithm generate better inputs (not covered in this article).

It’s worth pointing out that checking blocks alone is not a complete solution. This is because an if-statement’s immediate parent is not necessarily a block. For example, you can have an if-statement defined with in the body of a case clause, which is NOT of type *ast/BlockStmt. Our example code does not have to worry about these situations, but if we wanted to make our solution more generalizable, we would need to consider these edge cases.

For step 3, we need to briefly cover how to write the instrumented code back to disk. Reading source code from disk into an AST wasn’t so bad, how hard can it be to do the reverse? Turns out, not bad at all!

The go/format standard library package defines the Node function, which allows us to format our AST in canonical gofmt style, and write the result to disk. Let’s take a look at the function signature:

func Node(dst io.Writer, fset *token.FileSet, node any) error

Here’s a breakdown of each argument.

  1. dst: Any type that implements the io.Writer interface. For our purposes, we can pass in an instance of os.File to write to disk.
  2. fset: If you recall, ParseFile had a parameter of the same type. Thus, we can reuse the same file set argument we passed into ParseFile here. (In our previous examples, we passed in token.NewFileSet() directly to ParseFile. Instead of doing that, we will store the result of that call in a variable, and pass that variable to both functions).
  3. node: For our case, we will pass in our AST, the result of calling ParseFile, which is of type *ast.File. This function is capable of processing other types of nodes, see the docs for more information.

With that, we now have enough information to understand how instrumentation works at a high level. The following example should mostly make sense (there are a couple details I did not have time to cover here in detail):

package main

import (
	"fmt"
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"
	"io"
	"os"
	"strconv"
)

var fset *token.FileSet

// printUsage prints usage information to w.
func printUsage(w io.Writer) {
	fmt.Fprintln(w, `usage: ./cmd/instrument/main [source filepath] [destination filepath]

source filepath: A filepath to Go source code you wish to instrument.
destination filepath: A filepath where instrumented Go code will live.
`)
}

// makeStmt returns the statement to execute prior to each if-statement.
// It takes the line and column numbers as input, and prints out both as a
// comma-separated list to stdout.
func makeStmt(line, col string) ast.Stmt {
	return &ast.ExprStmt{
		X: &ast.CallExpr{
			Fun: &ast.SelectorExpr{
				X:   ast.NewIdent("fmt"),
				Sel: ast.NewIdent("Printf"),
			},
			Args: []ast.Expr{
				&ast.BasicLit{Kind: token.STRING, Value: `"%d,%d\n"`},
				&ast.BasicLit{Kind: token.INT, Value: line},
				&ast.BasicLit{Kind: token.INT, Value: col},
			},
		},
	}
}

// instrument takes a list of statements, and for each `ast.IfStmt`, an
// additional, instrumented line is added.
func instrument(list []ast.Stmt) []ast.Stmt {
	out := make([]ast.Stmt, 0, len(list))
	for _, s := range list {
		if ifStmt, ok := s.(*ast.IfStmt); ok {
			start := fset.Position(ifStmt.Pos())
			line, col := strconv.Itoa(start.Line), strconv.Itoa(start.Column)
			out = append(out, makeStmt(line, col))
		}
		out = append(out, s)
	}
	return out
}

func main() {
	// read filename as cli arg
	args := os.Args[1:]
	if len(args) < 2 {
		printUsage(os.Stderr)
		os.Exit(1)
	}
	source, dst := args[0], args[1]

	// step 1: read file from disk, and parse as AST
	fset = token.NewFileSet()
	f, err := parser.ParseFile(fset, source, nil, parser.SkipObjectResolution|parser.ParseComments)
	if err != nil {
		fmt.Fprintf(os.Stderr, "problem parsing source file: %s\n", err.Error())
		os.Exit(1)
	}

	// step 2: perform instrumentation
	fmt.Printf("successfully parsed source file %s! instrumenting if-statements...\n\n", source)
	for n := range ast.Preorder(f) {
		if block, ok := n.(*ast.BlockStmt); ok {
			block.List = instrument(block.List)
		}
	}

	// create tmp file to write instrumented source code to
	dstFile, err := os.Create(dst)
	if err != nil {
		fmt.Fprintf(os.Stderr, "problem create tmp file: %s\n", err.Error())
		os.Exit(1)
	}
	defer dstFile.Close()

	// step 3: write AST back out as source code to disk
	err = format.Node(dstFile, fset, f)
	if err != nil {
		fmt.Fprintf(os.Stderr, "problem formatting ast: %s\n", err.Error())
		os.Exit(1)
	}
	fmt.Printf("instrumentation complete! new source written to: %s\n", dst)
}

In this code, we can see the 3 steps I described above. We start by parsing the file into an AST, similar to previous examples. Next, we perform the instrumentation. We do the traversal using Preorder. On each iteration, we use type assertions to build the logic we need for this particular instrumentation. We add new statements, when necessary, to each block’s list List of statements. Finally, we use the Node function to write out our formatted AST back to disk, at a separate file location.

If you are following along, replace the contents of cmd/instrument/main.go with the above. We need to create a new location to store our instrumented source code, so we will create a new directory, alongside the compilation and run steps from earlier:

mkdir /tmp/instrument
go build -o ./cmd/instrument/main ./cmd/instrument/main.go
./cmd/instrument/main main.go /tmp/instrument/main.go

After executing the above, you should see the following output:

successfully parsed source file main.go! instrumenting if-statements...

instrumentation complete! new source written to: /tmp/instrument/main.go

You should also see a new file generated at /tmp/intrument/main.go. It will be identical to your original source, but you should notice print statements placed immediately before each if-statement.

We can finally run the instrumented version of our source! We have a couple options for this:

  1. Run go run /tmp/instrument/main.go [arg1] [arg2].

  2. Utilize the -overlay build flag. This is a neat option! If you are only interested in running the instrumented version of the code, rather than having to remember the temporary path each time you want to execute, you can create an overlay JSON file, which allows us to tell the Go compiler to refer to the instrumented source rather than our primary source. First, create the overlay JSON file, overlay.json, at the root of the project:

    {
        "Replace": {
            "main.go": "/tmp/instrument/main.go"
        }
    }

    Then, all you have to do is call go build with the overlay flag:

    go build -overlay=overlay.json main.go

    And when you execute the main binary directly, it will execute our instrumented code, likeso:

    ./main 1 2

For myself, I went with option 2. Let’s take a look at some example outputs of our instrumented program.

./main 1 2  
19,2
24,2
29,2
39,2
53,2

./main 2 2
19,2
24,2
29,2
39,2
53,2
54,3
4

./main 75 75
19,2
24,2
29,2
39,2
53,2
54,3
55,4
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x105083188]

goroutine 1 [running]:
main.main()
        .../instrumentation/main.go:68 +0x258

As we can see from the output, each if-statement’s location is properly being printed to stdout. As we provide different inputs to the program, some new if-statements are reached. Finally, we see that some inputs cause our program to crash.

You might notice that the column numbers seem off. This is because Go uses tabs for indentation, and each tab is a single character. Therefore, even if it looks like an if-statement starts at column 4 or 8 in your editor, it’s actually only 1 or 2 bytes offset from the left-side of the screen respectively. You can get the “visual” column number, but it requires some cross-checking against the source file, alongside your preference for how many columns the editor renders for each tab.

A next step from here would be to implement a fuzzing technique to discover which inputs cause the program. The fuzzing algorithm might:

  • Starts with random inputs
  • Repeatedly runs the instrumented program
  • Analyze how different, randomized inputs impact the instrumentation (i.e., number of branches hit)
  • Use results of instrumentation to refine how it chooses inputs, so we select for inputs that hit more if-statements

I will leave this as an exercise to the reader, as the focus of this article is simply the instrumentation piece. If requested, I’d be happy to write a follow-up article on fuzzing!

Final words

I decided to write this article after my experience in CS 6340 - Software Analysis (OMSCS), a class I took this semester. This is a really neat course that covers many software analysis techniques, most of which have an associated lab that solidify each technique.

I took this course in response to the direction the tech world is moving in. I suspect that as we hand off more and more of code implementation to AI, the job of software engineers will shift more toward verifying that the generated software is correct. Software Analysis give us a variety of automated techniques to catch all kinds of bugs, so it’s nice to now have some of these under my toolbelt.

While instrumentation itself is not an analysis technique, many software anaylsis techniques use the results of instrumented code to perform their anaylsis. The course focused on instrumenting code using LLVM (you can probably tell from the introduction of this article), but I decided to take some time to see if I could figure out how to apply what I learned from the course in a language I work with daily: Go. Turns out, you can, and it’s argubly easier than what we learned in class. If I hadn’t taken this course, however, I probably would have never thought to check out instrumentation in Go!

If you found this article interesting, and are a student in the OMSCS program, I highly recommend taking this course!