I have several threads and each thread writes output to stdout. However I want to redirect the ouput of each thread to a separate file independently of each other, then merge them to keep he flow of each thread together.
What I mean is the following:
Thread1 writes every print, every exception and every other ouput into file1.log Thread2 writes every print, every exception and every other ouput into file2.log and so on. So what I'm looking for is to set the stdout for each thread exclusivly. However setting the stdout only works globally mean that Thread1 and Tread2 will always write to the same defined stdout. I have not found out yet how to do this. I can't use processes though, because f another issue.
How can I do that?
The Python
logging
module is thread-safe.Use it to create an individual logger for each thread, and register a
FileHandler
to (also) log to a file:Here's a more complete example:
This will give you five logfiles,
thread-1.log
throughthread-5.log
, containing only the output of the respective thread:thread-1.log
If you still want to log to the console, simply create a
StreamHandler
and attach it to your logger:This will log to
STDERR
by default. If you wantSTDOUT
, useFor more information on using the Python
logging
module, see the Advanced Logging Tutorial.