How to redirect tracepoint output to a file in Ruby?

122 views Asked by At

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") }
1

There are 1 answers

0
CSMan On BEST ANSWER

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") }