Try to define redirect_to_logging so that it detects recursion

Currently it can happen that using redirect_to_logging leads to an infinite loop because it can happen that stdout gets redirected to logging which then prints it to stdout, which is being redirected to logging, which ...

Current comment in the code:

If you are using logging.StreamHandler in your logging configuration (e.g., to output logging to a console), it is important that you configure it before using this context manager so that initial stderr is stored by the handler, before the context manager swaps it. Otherwise you will get into a recursive loop.

It would be useful to see if we can somehow prevent this to happen and remove this requirement. Because sometimes it is hard to control who and how and when initializes logging. Moreover, if it does happen, if you do not know about this requirement, this error seems pretty tricky to debug.

We use redirect_to_logging in capturing stdout during primitive run for the purposes of pipeline run recording.