multithreadingruststdoutpanic

Redirect stdout and stderr streams of a thread


I am building a cli tool where application would perform multiple tasks by spawning threads. One of these threads would handle the rendering of state of application. The way rendering works is simply an infinite loop where state is rendered and the screen is cleared using ASCII escape codes.

What I want to add is also show a "logs" section in my rendering that shows any stdout and stderr (and even panic traces) messages written by any of the other thread because currently whatever is written is wiped out because of the clear screen logic of the rendering, so I need to redirect any output from threads to a dedicated field in application state.

I know I can create a custom buf writer and pass it to each thread where it can write all logs to it instead of std streams but I don't know how that would capture panics and stacktraces.


Solution

  • This is generally impossible. libtest does this, but it does so using an internal perma-unstable machinery that can forward println!() etc. (it won't capture output by FFI code, though).

    The easiest way is, as you've already noticed, to pass a stream to the thread. Capturing panic information can be done by changing the panic hook.