There are a ton of resources on how to manage sys.stdout
so that it prints to either just a file or tees to both a file and sys.stdout
. However, my use case is different.
I am using code from a code base that uses print
calls, and it would take too long to swap it out for a logger. Instead, I created a custom Tee
class to duplicate output from print
calls to a log file. It worked fine for the synchronous case.
Template for Tee
class: How to duplicate sys.stdout to a log file?
However, I adapted the code to use multiple threads at once using the multiprocessing
module. Because of this, I am unable to track which thread the print
calls are coming from, and therefore which Tee
to use.
It would be really useful to be able to redirect print
calls, but only from within a certain block of code. For example, if I create a Tee
class inside a function and then delete it, then all print
calls within that function and their children would redirect to a specific file, whereas if I create a Tee
class inside another thread, the same would happen.
I can imagine a complicated class using locks and synchronization to manage everything, but I am stuck on how to determine the origin of the print
calls. Any suggestions?