7

I am trying to store logs from multiple threads into a single file. But in my log file, logs from different threads are getting merged. I don't want separate log files for different threads. But when one thread is writing logs to the file, the other thread should wait till the previous thread finishes writing all the logs. I have tried different ways to do so, but finally didn't find appropriate solution.

from threading import Thread, current_thread
import threading
import time
import logging


logging.basicConfig(filename='LogsThreadPrac.log', level=logging.INFO)
logger = logging.getLogger(__name__)


def worker(val):
    print('value from the thread: {}'.format(val))
    logger.info('+++++++++++++++++++++++++++++++++++++++')
    print(current_thread().name)
    logger.info('value from the thread: {}'.format(val))
    time.sleep(3)
    logger.info('+++++++++++++++++++++++++++++++++++++++')

t1 = Thread(target=worker, args=[1,], name='th'+str(1))
t1.start()
t2 = Thread(target=worker, args=[2,], name='th'+str(2))
t2.start()
1
  • What is your use case? The logging module is not intended to deal with synchronisation requirements of higher layers of abstraction. Commented Feb 12, 2018 at 11:40

1 Answer 1

2

You could pass a Lock as an argument to your workers, so you manage to synchronize the threads the way you want.

from threading import Thread, current_thread, Lock
import threading
import time
import logging


logging.basicConfig(filename='LogsThreadPrac.log', level=logging.INFO)
logger = logging.getLogger(__name__)
logger_lock = Lock()

def worker(val, lock):
    print('value from the thread: {}'.format(val))
    with lock:
        logger.info('+++++++++++++++++++++++++++++++++++++++')
        print(current_thread().name)
        logger.info('value from the thread: {}'.format(val))
        time.sleep(3)
        logger.info('+++++++++++++++++++++++++++++++++++++++')
t1 = Thread(target=worker, args=[1, logger_lock], name='th'+str(1))
t1.start()
t2 = Thread(target=worker, args=[2, logger_lock], name='th'+str(2))
t2.start()

You can check more about the lock uses and examples here

Sign up to request clarification or add additional context in comments.

3 Comments

This solution is going to take at least 6 seconds to finish both workers, which is pretty much the same time it takes without using threading.
The reason is that the threads are accessing the same file and waiting for them. This is not a true concurrency design.
Guess you guys don't really understand the problem of concurrency and how did the guy wanted to apply it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.