User12547645
User12547645

Reputation: 8497

How can I print functions as they are being called?

I am new in a large complicated codebase. I would like to follow a request as it is being processed. For this I'd like to have a feature that enables printing each function that is being called without having to add trace functionality everywhere in the codebase (see e.g. crate trace).

Ideally I would like exactly this python solution, but in rust (see SO post):

def tracefunc(frame, event, arg, indent=[0]):
      if event == "call":
          indent[0] += 2
          print("-" * indent[0] + "> call function", frame.f_code.co_name)
      elif event == "return":
          print("<" + "-" * indent[0], "exit function", frame.f_code.co_name)
          indent[0] -= 2
      return tracefunc

import sys
sys.setprofile(tracefunc)

main()   # or whatever kicks off your script

EDIT:
A tool that does this may even be better. See e.g. this solution for C++

Upvotes: 1

Views: 383

Answers (1)

Code4R7
Code4R7

Reputation: 2968

You could put a panic!() macro in your code, to get a backtrace. You will also need to set the backtrace option with export RUST_BACKTRACE=1 or export RUST_BACKTRACE=full before you execute your program (cargo run).

A way to get a live trace of a running Rust program is through logging. You might want to try the log crate, in conjunction with the syslog crate. Make use of the macros debug!(), info!(), warn!(), and error!() to log messages. You can use the name of the current function if you wish.

Then configure rsyslog to route the messages from your application to a separate logfile, which you can monitor live with something like tail -f /var/log/<yourapp.log> in a separate terminal.

Upvotes: 1

Related Questions