Emitting Logs
msg! and sol_log_data write to transaction logs consumed by explorers, indexers, and simulations. Use sparingly - each log spends compute units.
Recipe
solana_program::msg!("vault deposit {}", amount);When to reach for this:
- Debugging failing instructions in devnet.
- Correlating on-chain steps with off-chain analytics.
- Temporary instrumentation during audit fixes.
Working Example
pub fn deposit(amount: u64) -> ProgramResult {
solana_program::msg!("deposit_start amount={}", amount);
if amount == 0 {
solana_program::msg!("deposit_reject zero");
return Err(ProgramError::InvalidArgument);
}
solana_program::msg!("deposit_ok");
Ok(())
}What this demonstrates:
- Structured prefix tokens help grep logs.
- Reject path logs before error return.
- Remove or gate verbose logs before mainnet.
Deep Dive
CU Cost
Logs scale with string length and count.
Alternatives to Logs
- Custom errors for users
- Anchor events for indexers
Rust Notes
solana_program::log::sol_log_data(&[b"evt", &amount.to_le_bytes()]);Gotchas
- Logs in loops - CU explosion.. Fix: Log summary only.
- Sensitive data - Logs are public.. Fix: Never log secrets or full PII.
- Relying on logs for control flow - Logs are not consensus inputs.. Fix: State must encode truth.
- Format panics - Bad format is dev error.. Fix: Use simple literals in prod.
- Production noise - Hard to index.. Fix: Prefer events with schema.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
Anchor emit! | Structured events | Native only |
| Custom error codes | User UX | Internal debug |
| Off-chain simulation traces | Dev only | Production observability |
FAQs
Where appear?
Transaction meta logMessages.
Max log length?
Bounded by CU and tx limits.
msg vs sol_log_data?
后者 for binary chunks.
Index logs?
Geyser/webhooks parse log lines.
Feature flag logs?
Common for release builds.
Logs on fail?
Still emitted before failure point.
Multiple programs?
All logs merged in order.
Simulate shows logs?
Yes with simulateTransaction.
Agave 4.1.1 changes?
Re-profile CU if logging heavily.
Replace with events?
For indexer-first design yes.
Debug only macro?
Wrap msg! in cfg.
Log PDA bump?
OK short term for debug.
Related
- Logging with msg! - CU-aware logging
- Emitting Events - Structured events
- Debugging Failed Transactions - Reading output
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.