Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e10d370

Browse files
committed
Added simple threading example to logging cookbook.
1 parent f817a48 commit e10d370

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Doc/howto/logging-cookbook.rst

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,61 @@ The output looks like this::
9494
2005-03-23 23:47:11,673 - spam_application - INFO -
9595
done with auxiliary_module.some_function()
9696

97+
Logging from multiple threads
98+
-----------------------------
99+
100+
Logging from multiple threads requires no special effort. The following example
101+
shows logging from the main (initIal) thread and another thread::
102+
103+
import logging
104+
import threading
105+
import time
106+
107+
def worker(arg):
108+
while not arg['stop']:
109+
logging.debug('Hi from myfunc')
110+
time.sleep(0.5)
111+
112+
def main():
113+
logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
114+
info = {'stop': False}
115+
thread = threading.Thread(target=worker, args=(info,))
116+
thread.start()
117+
while True:
118+
try:
119+
logging.debug('Hello from main')
120+
time.sleep(0.75)
121+
except KeyboardInterrupt:
122+
info['stop'] = True
123+
break
124+
thread.join()
125+
126+
if __name__ == '__main__':
127+
main()
128+
129+
When run, the script should print something like the following::
130+
131+
0 Thread-1 Hi from myfunc
132+
3 MainThread Hello from main
133+
505 Thread-1 Hi from myfunc
134+
755 MainThread Hello from main
135+
1007 Thread-1 Hi from myfunc
136+
1507 MainThread Hello from main
137+
1508 Thread-1 Hi from myfunc
138+
2010 Thread-1 Hi from myfunc
139+
2258 MainThread Hello from main
140+
2512 Thread-1 Hi from myfunc
141+
3009 MainThread Hello from main
142+
3013 Thread-1 Hi from myfunc
143+
3515 Thread-1 Hi from myfunc
144+
3761 MainThread Hello from main
145+
4017 Thread-1 Hi from myfunc
146+
4513 MainThread Hello from main
147+
4518 Thread-1 Hi from myfunc
148+
149+
This shows the logging output interspersed as one might expect. This approach
150+
works for more threads than shown here, of course.
151+
97152
Multiple handlers and formatters
98153
--------------------------------
99154

0 commit comments

Comments
 (0)