How can I log data to the console from my contract?

What is the equivalent of console.log() in Sway?

There are two main ways to be able to log data in a contract to the console.

  1. You can return the data in the function, and print the value returned to the console.

  2. Use the log method from the standard library. When a function gets called that uses the log method, a log or logData receipt will be appended to the transaction receipts array. Each call to log appends a receipt to the list of receipts.

fn test_function(){
	let x: u64 = 64;
	let boolean = true;
	let string = "fuel";

In a Rust test you can print the log values either from the receipts array, or with the get_logs or get_logs_with_type methods. Due to possible performance hits, it is not recommended to use get_logs() outside of a debugging scenario.

let response = instance.methods().test_function().call().await.unwrap();

println!("FIRST LOG: {:?}", response.receipts[1].ra());

let log_string = response.get_logs_with_type::<SizedAsciiString<4>>();
println!("LOG STRING: {:?}", log_string);

println!("GET LOGS: {:?}", response.get_logs());

This will print the following to the console:

FIRST LOG: Some(64)
LOG STRING: Ok([SizedAsciiString { data: "fuel" }])
GET LOGS: Ok(["64", "true", "SizedAsciiString { data: \"fuel\" }"]))

You can learn more about working with logs in the Rust SDK here: Logs - The Fuel Rust SDK


Something like this can also be useful to print everything:

response.receipts.iter().for_each(|r| match r.ra() {
        Some(r) => println!("{:?}", r),
        _ => (),