0

Is there a way to alter the print statement in Python to include the thread name before any printed message?

Currently my print statements look like

print("[%s] Some text... " % self.name)
>> [thread_name] Some text...

I have a multithreaded web server where I track some behavior from each thread and it quickly gets tedious adding the above pattern to each print statement. Is there a quick way to redefine the print() function like this?

dbm
  • 35
  • 1
  • 6
  • 2
    Perhaps by using `logging` instead of `print(...)`. See https://docs.python.org/3/howto/logging-cookbook.html#logging-from-multiple-threads –  Nov 26 '20 at 13:41
  • 1
    This might be useful for you: https://stackoverflow.com/questions/22643337/per-thread-logging-in-python – Serial Lazer Nov 26 '20 at 13:41
  • I assume you have a common class that you're instantiating for each thread? Or where exactly is `self.name` coming from? – Karl Knechtel Nov 26 '20 at 13:46
  • @KarlKnechtel Yes, each thread is a class instance inheriting from `threading.Thread`, where I `self.name` them according to what they do. – dbm Nov 26 '20 at 14:29

0 Answers0