Per thread logging in python

前端 未结 5 1713
逝去的感伤
逝去的感伤 2021-01-13 05:03

Consider a multi threaded python application using python logger module. I want to do per thread logging, so I have appended the a unique-ID (not thread id) at the bottom of

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 05:35

    Although, I am not really experienced in what I am suggesting, I would try to use Thread-local storage.

    Thread-local storage

    A class that represents thread-local data. Thread-local data are data whose values are thread specific. To manage thread-local data, just create an instance of local (or a subclass) and store attributes on it. The instance’s values will be different for separate threads.

    You can then save and access the variables in the following way:

    import threading
    mydata = threading.local()
    mydata.x = 1
    

    I suggest to save the thread-specific logger to the thread-local variable when you create it and then access the logger again when necessary through the thread-local storage.

    Have a look, it helped me to understand thread-local:

    • Thread local storage in Python
    • What is “thread local storage” in Python, and why do I need it?

提交回复
热议问题