30

Sometimes it would be really helpful to be able to see string representations of variable values in the Geth console, like of argument values in functions. Can I somehow print them to the Geth console?

19

You are most likely looking for Events. Not only do they help with debugging, but they are useful in normal production code.

Events are declared like functions, like so:

event VoteCast(address voter, uint votes, bool inFavor);

Then somewhere (for example, in a vote counting function):

function vote(bool inFavor) {
    var votes = shares[msg.sender];
    // ...
    emit VoteCast(msg.sender, votes, inFavor);
}

In javascript, a contract object has an event method, which can be used to read events when they happen. In fact, it can read events that happened in the past.

var voteCast = someContract.voteCast();
voteCast.watch(function(err, result) {/* some callback */});
// Alternately, to get the events all at once.
voteCast.get(function(err, result) /* some other callback* /)

Events have a number of quirks, which are too many to get into detail here. Nonetheless, they're an integral part of high-level dapp work.

12

EDIT: logX is deprecated and doesn't appear in Solidity 0.8+ documentation. The bellow example is only working if using Solidity up to version 0.7.6 and should now be replaced by Events or Solidity libraries enabling the use of console.log() inside your contract code.

Since my first answer, many projects improved the debug experience:


Deprecated answer

Print doesn't exist in Solidity. Use the logX statement as indicated in the manual instead.

2
  • 1
    The log statements are really low level. One is better off using specific events. Jul 17 '16 at 16:10
  • 5
    Agree they're low-level but can be useful especially for temporary debugging to quickly see a value in IDEs that support log statements and pretty-print their parameters.
    – eth
    Nov 9 '16 at 11:06
1

Since you mentioned geth console, you can try console.log() for debugging purposes:

console.log ("Your debug message" + debug.object);

This is possible because geth supports web3.js

3
  • 3
    this is js way , not solidity Sep 10 '18 at 13:02
  • @MaxLXJ print is not supported by Solidity as it supports Events-driven paradigm, but since it leverages JavaScript syntax it is quite handy to use console.log for debug purposes. But this is not recommended for Production/Live usage as Solidity written contract will be distributed across nodes, and using Events will be ideal.
    – CᴴᴀZ
    Sep 20 '18 at 11:06
  • It's true that is not solidity, but probably it's what most people want: an easy way to print something in the console. This works if you write the console.log in the console and not in the solidity code. Aug 7 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.