Logging with msg!
msg! writes human-readable lines to transaction logs. Useful for development and ops, but each call costs compute units - budget logs like any hot-path code.
Recipe
solana_program::msg!("swap in={} out={}", amount_in, amount_out);When to reach for this:
- Debugging devnet failures.
- Correlating on-chain steps with support tickets.
- Temporary instrumentation during incident response.
Working Example
#[cfg(feature = "verbose_logs")]
macro_rules! vlog { ($($t:tt)*) => { solana_program::msg!($($t)*) }; }
#[cfg(not(feature = "verbose_logs"))]
macro_rules! vlog { ($($t:tt)*) => {}; }What this demonstrates:
- Feature-gated logs for release builds.
- Macro no-ops when disabled.
- Production path stays quiet.
Deep Dive
CU Impact
Logs charge per syscall + bytes.
Binary Logs
sol_log_data for compact key/value.
Rust Notes
// Prefer fixed prefixes: "MYPROG:step1"Gotchas
- Logs in tight loop - CU exceeded.. Fix: Aggregate outside loop.
- PII in logs - Public chain data.. Fix: Redact.
- Rely on logs for auth - Attacker sees same logs.. Fix: State is truth.
- Format user strings - Injection irrelevant but costly.. Fix: Log hashes or ids.
- Leave debug logs on mainnet - Noise and cost.. Fix: Feature flags.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Custom errors only | User-facing | Internal debug |
| Anchor events | Indexer-friendly | CU still applies |
| Off-chain simulation | Dev | Prod |
FAQs
msg CU cost?
Non-trivial - simulate.
Explorer shows?
Yes logMessages.
log_data?
Binary slices.
Anchor msg?
Same syscall.
Pinocchio?
Syscall log.
Max logs?
Tx limit + CU.
Structured logging?
Events better.
Index logs?
Geyser plugins.
Remove for mainnet?
Recommended or gate.
Sim vs live?
Same.
Agave 4.1.1?
Re-profile after upgrade.
Surfpool?
Shows logs in trace.
Related
- Emitting Logs - Native angle
- Emitting Events - Structured
- Debugging Failed Transactions - Workflow
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.