summaryrefslogtreecommitdiffstats
path: root/Doc/howto
diff options
context:
space:
mode:
authorVinay Sajip <vinay_sajip@yahoo.co.uk>2016-02-20 19:03:29 (GMT)
committerVinay Sajip <vinay_sajip@yahoo.co.uk>2016-02-20 19:03:29 (GMT)
commitd9dc53021e11c357592f7ecc4aa9e5dba9bcd359 (patch)
tree3de91f67e23e475e5e88c69ebd882fad51131815 /Doc/howto
parent2d2d08d2cc2af98219fd105ec75fa58a633d2b75 (diff)
parente10d370a929a80bc0708daea4bf4bc0715da9706 (diff)
downloadcpython-d9dc53021e11c357592f7ecc4aa9e5dba9bcd359.zip
cpython-d9dc53021e11c357592f7ecc4aa9e5dba9bcd359.tar.gz
cpython-d9dc53021e11c357592f7ecc4aa9e5dba9bcd359.tar.bz2
Merged cookbook update from 3.5.
Diffstat (limited to 'Doc/howto')
-rw-r--r--Doc/howto/logging-cookbook.rst55
1 files changed, 55 insertions, 0 deletions
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst
index b979aa7..44718d5 100644
--- a/Doc/howto/logging-cookbook.rst
+++ b/Doc/howto/logging-cookbook.rst
@@ -94,6 +94,61 @@ The output looks like this::
2005-03-23 23:47:11,673 - spam_application - INFO -
done with auxiliary_module.some_function()
+Logging from multiple threads
+-----------------------------
+
+Logging from multiple threads requires no special effort. The following example
+shows logging from the main (initIal) thread and another thread::
+
+ import logging
+ import threading
+ import time
+
+ def worker(arg):
+ while not arg['stop']:
+ logging.debug('Hi from myfunc')
+ time.sleep(0.5)
+
+ def main():
+ logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
+ info = {'stop': False}
+ thread = threading.Thread(target=worker, args=(info,))
+ thread.start()
+ while True:
+ try:
+ logging.debug('Hello from main')
+ time.sleep(0.75)
+ except KeyboardInterrupt:
+ info['stop'] = True
+ break
+ thread.join()
+
+ if __name__ == '__main__':
+ main()
+
+When run, the script should print something like the following::
+
+ 0 Thread-1 Hi from myfunc
+ 3 MainThread Hello from main
+ 505 Thread-1 Hi from myfunc
+ 755 MainThread Hello from main
+ 1007 Thread-1 Hi from myfunc
+ 1507 MainThread Hello from main
+ 1508 Thread-1 Hi from myfunc
+ 2010 Thread-1 Hi from myfunc
+ 2258 MainThread Hello from main
+ 2512 Thread-1 Hi from myfunc
+ 3009 MainThread Hello from main
+ 3013 Thread-1 Hi from myfunc
+ 3515 Thread-1 Hi from myfunc
+ 3761 MainThread Hello from main
+ 4017 Thread-1 Hi from myfunc
+ 4513 MainThread Hello from main
+ 4518 Thread-1 Hi from myfunc
+
+This shows the logging output interspersed as one might expect. This approach
+works for more threads than shown here, of course.
+
Multiple handlers and formatters
--------------------------------