Microblog: Debug logging in Anchor and Solana

Search for a command to run...

No comments yet. Be the first to comment.
https://youtu.be/z4TzkuKLWAA Transcript Intro Hey, this is Sohrab, head of engineering for Lab Eleven. Today, I want to go through the basics of Solana transactions and I will be using Better Call Sol as a visual aid. You can find me on Twitter by ...

This article has been written with Anchor v0.24.x in mind. We will endeavour to keep this information updated as things evolve. Anchor framework is quickly becoming the de facto approach to building Solana on-chain programs. Its abstractions offer s...

Jumping into Solana programming can seem somewhat daunting. These tips and pointers should help you along with your exciting new chapter. Local Development The book already calls out the required software for building Anchor programs. I highly recom...

We’ve written about why we’re getting behind the web3 movement, and our ambition to become the world’s best Solana delivery partner. Like any startup, success depends on focus, and our focus is Solana. But the question remains - why are we putting al...

Logging can be expensive for programs deployed to Solana or logs may contain sensitive information that should not be available during the normal operation of a program.
In these scenarios, we miss having different log levels, as we are used to with other application frameworks. In this micro-post, we will implement this feature for both Anchor and plain Solana applications.
We will try to keep things simple: introduce a macro that includes or omits logs based on a Cargo feature.
The debug macro, for Anchor programs, is implemented as below:
#[macro_export]
macro_rules! debug {
($($rest:tt)*) => {
#[cfg(feature="verbose")]
anchor_lang::prelude::msg!($($rest)*)
};
}
The macro checks for the verbose Cargo feature and includes the logging statement if it is enabled.
For this to work, you will need to declare a verbose feature in the program's Cargo.toml:
[features]
...
verbose = []
...
Now you can use this feature in your code:
debug!("some super detailed info");
debug!("the secret is {}", secret);
We can build binaries with or without debug logging using the following Anchor commands:
# with debug logging
anchor build -- --features verbose
# without debug logging
anchor build
Unfortunately, both anchor build and anchor test run Cargo builds with --release flag so we have to be explicit about enabling the feature.
The differences are minimal between Anchor and non-Anchor versions.
The debug macro is defined as below:
#[macro_export]
macro_rules! debug {
($($rest:tt)*) => {
#[cfg(debug_assertions)]
solana_program::msg!($($rest)*)
};
}
Here we use the standard debug_assertions conditional compilation instead. This removes the need for defining custom features and can be controlled by the standard Cargo profiles.
And cargo commands are used for the build:
# with debug logging
cargo build
# without debug logging
cargo build --release