Log Some Data

From

editione1.0.1

Updated August 7, 2023

As youโ€™re reading through code, you will need to hold a mental model of the data in the system and how it is manipulated as the business logic is applied. Some code may be easy to follow, but you may find yourself deep in the codebase without any idea what the data looks like when it reaches a certain function. In these situations, itโ€™s sometimes useful to lean on your logging system to print some data to your log files so that you can inspect it.

Add a few log statements with data youโ€™re interested in. This could be certain values of variables or object properties, or it could be an arbitrary text string that will give you some useful information if you see it in your logs. Either way, setting log statements throughout your code is a quick and easy way to get a snapshot of what your data structures look like at a point in time when the code is executing. Sometimes, a well-placed log statement can reveal a bug youโ€™ve been tracking down, or it can expose certain things that help you understand what the code is doing.

All programmers rely on logging to gain insight into what their code is doing, so donโ€™t feel like itโ€™s the wrong way to debug your code. Even the most experienced engineers rely on logging when theyโ€™re developing new features or tracking down a hard-to-find bug.

Fire Up Your Debugger

Occasionally, youโ€™ll come across code that you wonโ€™t understand no matter how many log statements you add. Wrapping your head around confusing code is frustrating, especially if youโ€™re trying to figure out how some piece of data is being manipulated. While you may be able to figure it out with enough log statements, itโ€™s messy to add them all over your codebase just to piece together whatโ€™s going on. Sometimes a debugger is the better tool for the job.

When you distill a program down to the simplest form, itโ€™s really just taking some inputs, manipulating the data structures, and producing output somewhere. To really get a grasp on how everything works, you need to understand how the data changes as it moves through the system. While itโ€™s helpful to read through code and build a mental model of what the data structure looks like, itโ€™s sometimes easier to visualize the program with a debugger and observe how the data changes as it moves through the system.

If you have a debugger configured, youโ€™ll be able to see what the data looks like at each breakpoint you set. As you step through the debugger, focus on the data and how it changes as you step in and out of functions.

Youโ€™re reading a preview of an online book. Buy it now for lifetime access to expert knowledge, including future updates.
If you found this post worthwhile, please share!