0

I am using the TracePoint class to trace a specific method in a large project, however, I need to also interact with the console the project provides. Although interaction works. I need to see any prompts the console makes, which is not possible due to the output of the tracepoint (there are A LOT of method calls).

Therefore, I would like to redirect the output of the Tracepoint to another file (for example another terminal's tty but not necessarily).

Is there a way to achieve this?

As an example, I have the following: I would like to keep all outputs normal, except for the ones done by Tracepoint.

def start_trace
    trace =
    TracePoint.new(:call) { |tp| p [tp.path, tp.lineno, tp.event, tp.method_id] }
    trace.enable
    yield
    trace.disable
  end


def fun1
    puts("This is fun1")
end

def fun2
    puts("This is fun2")
end

def fun3(num)
    puts("This is fun3: " + num)
    fun2
end

start_trace { fun3("bye") }
CSMan
  • 11
  • 3
  • In your code, you are using `p`, which writes to stdout. Just use here a different method, if you want to write the output to a different stream. – user1934428 Jun 03 '22 at 12:36
  • @user1934428 where do I find info on what redirection is available? Or how do I redirect it to a specific file? – CSMan Jun 03 '22 at 16:13
  • I would pass an object of type `File` to your class which uses the Trace. Let's call this variable `@destination`. Then, instead of doing simply a `p`, you are doing a `@destination.p(....)`, respectively `@destination.puts(...)`. – user1934428 Jun 07 '22 at 06:29

1 Answers1

0

As a comment said, the p prints to stdout. To redirect the output to another TTY (or another file), the file needs to be opened and the .print method can be used. The following code gets the desired functionality:

def start_trace
    file = File.open("/dev/ttys007", "w")
    trace =
    TracePoint.new(:call) { |tp| 
        file.print [tp.path, tp.lineno, tp.event, tp.method_id]
        file.puts()
    }
    trace.enable
    yield
    trace.disable
    file.close
  end


def fun1
    puts("This is fun1")
end

def fun2
    puts("This is fun2")
end

def fun3(num)
    puts("This is fun3: " + num)
    fun2
end

start_trace { fun3("bye") }
CSMan
  • 11
  • 3