Last active
May 19, 2020 15:23
-
-
Save mjpieters/2c73b6f6ed31bc426a8786c0339c18bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from config import ThreadFilter, IgnoreThreadsFilter # noqa: F401 | |
import logging | |
import threading | |
import time | |
# Attach the IgnoreThreadsFilter to the main root log handler | |
# This is responsible for ignoring all log records originating from | |
# new threads. | |
main_handler = logging.FileHandler("/tmp/mainlogfile.log", 'a') | |
main_handler.addFilter(IgnoreThreadsFilter()) | |
logging.basicConfig(handlers=[main_handler], | |
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', | |
datefmt='%H:%M:%S', | |
level=logging.DEBUG) | |
log = logging.getLogger() | |
log.info("Running Urban Planning") | |
def thread_function(name): | |
# A dedicated per-thread handler | |
thread_handler = logging.FileHandler(f'/tmp/threadlogfile-{threading.get_ident()}.log', 'a') | |
formatter = logging.Formatter( | |
'%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
) | |
thread_handler.setFormatter(formatter) | |
# The ThreadFilter makes sure this handler only accepts logrecords that originate | |
# in *this* thread, only. It needs the current thread id for this: | |
thread_handler.addFilter(ThreadFilter(threadid=threading.get_ident())) | |
log.addHandler(thread_handler) | |
time.sleep(0.1) | |
hello(name) | |
def hello(name): # shared module on write time | |
log.info(name) | |
if __name__ == "__main__": | |
log.info("mainThread-start") | |
# consider giving the thread a name (add name=...), then you could | |
# use ThreadFilter(threadname=...) to select on all messages with that name | |
# The thread name does not have to be unique. | |
x = threading.Thread(target=thread_function, args=("thread==1",)) | |
x.start() | |
hello("mainThread-end") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment