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.
-
You can return the data in the function, and print the value returned to the console.
-
Use the
log
method from the standard library. When a function gets called that uses thelog
method, alog
orlogData
receipt will be appended to the transaction receipts array. Each call tolog
appends areceipt
to the list of receipts.
fn test_function(){
let x: u64 = 64;
log(x);
let boolean = true;
log(boolean);
let string = "fuel";
log(string);
}
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