We can use console.log() to print out debugging info in Foundry just like in JavaScript. Import the following library:
import "forge-std/console.sol";
Use console.log() in contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "forge-std/console.sol";
contract Counter {
uint public count;
// Function to get the current count
function get() public view returns (uint) {
return count;
}
// Function to increment count by 1
function inc() public {
console.log("Calling inc(). Now count = ", count);
count += 1;
}
// Function to decrement count by 1
function dec() public {
// This function will fail if count = 0
count -= 1;
}
}
Verbosity at least -vv must be used to print out console.log() messages:
forge test --match-path test/Counter.t.sol -vv
Of course you can also use console.log() in test file. For example, create a test file Console.t.sol:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
contract ConsoleTest is Test {
function testLogSomething() view public {
console.log("Log something here", 123);
}
}
No need to import forge-std/console.sol because it is included in forge-std/Test.sol, which is already imported.
Run test with -vv verbosity:
forge test --match-path test/Console.t.sol -vv
One caveat here: console.log() can not log int. There is another function named console.logInt() for doing this job:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
contract ConsoleTest is Test {
function testLogSomething() view public {
console.log("Log something here", 123);
int x = -1;
console.logInt(x);
}
}