My practice in Python multi-threading is rather poor. So, now, I'm studying how to get log info from multiple threads. I saw a lot of different approaches, but want to start from simple one, I guess. So the task is to create several threads and log data from each of them. In order to recognize the source of logs, I want to put some custom tag in the log output. I know that logging lib has a reach LogRecord attributes (thread, threadName etc.) and it works well. So, I've got some example (logging-from-multiple-threads) and make some modification. Here is a complete code:
import logging
import threading
import time
logger = logging.getLogger()
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(project)s : %(thread)x '
                              '%(levelname)-8s '
                              '%(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(syslog)
class ContextFilter(logging.Filter):
    def __init__(self, project):
        super(ContextFilter, self).__init__()
        self.project = project
    def filter(self, record):
        record.project = self.project
        return True
def worker(args):
    while not args['stop']:
        logging.debug('Hi from {}'.format(args['project']))
        time.sleep(0.5)
def main():
    projects = ['project_1', 'project_2']
    info = {'stop': False}
    threads = []
    for project in projects:
        info['project'] = project
        logger.addFilter(ContextFilter(project))
        thread = threading.Thread(target=worker, args=(info,))
        thread.start()
        threads.append(thread)
    while True:
        try:
            logging.debug('Hello from main')
            time.sleep(1.75)
        except KeyboardInterrupt:
            info['stop'] = True
            break
    for t in threads:
        t.join()
if __name__ == '__main__':
    main()
And here are the output results:
project_2 : 7fa627e77700 DEBUG    Hi from project_2
project_2 : 7fa6293d0700 DEBUG    Hello from main
project_2 : 7fa627676700 DEBUG    Hi from project_2
project_2 : 7fa627e77700 DEBUG    Hi from project_2
project_2 : 7fa627676700 DEBUG    Hi from project_2
project_2 : 7fa627e77700 DEBUG    Hi from project_2
project_2 : 7fa627676700 DEBUG    Hi from project_2
project_2 : 7fa627e77700 DEBUG    Hi from project_2
project_2 : 7fa627676700 DEBUG    Hi from project_2
project_2 : 7fa6293d0700 DEBUG    Hello from main
project_2 : 7fa627e77700 DEBUG    Hi from project_2
Actually, this is not what I was expecting. Can you give me some idea about what I am doing wrong?
 
     
     
     
    