1
+ """
2
+ We can use Python's logging module (https://docs.python.org/3/library/logging.html)
3
+ to print information to a console, file or the network to examine what is happening in the program
4
+
5
+ The advantage of using logging instead of other debugging techniques is that it is suitable to
6
+ be commited with the source and used in production
7
+
8
+ There is a lot of options we can use to configure where and how the information is printed,
9
+ e.g. there are several log levels (debug, info, error), several formatting options (%, str.format)
10
+
11
+ How to use:
12
+ - run the script with `python debug_with_default_logging.py`
13
+ - observe state (i, processed_word) and exception printed with additional info such as name of
14
+ the function or a line number
15
+ - observe that information is printed to the console and to a file at the same time
16
+ """
17
+
18
+ # The output:
19
+ # DEBUG process_words() 47 i=0, processed_word=Debugging
20
+ # DEBUG process_words() 47 i=1, processed_word=With
21
+ # DEBUG process_words() 47 i=2, processed_word=Default
22
+ # DEBUG process_words() 47 i=3, processed_word=Logging
23
+ # ERROR process_words() 49 The word is not a string
24
+
25
+ import logging
26
+
27
+ FORMAT = '%(levelname)-8s %(funcName)s() %(lineno)d\t %(message)s'
28
+ formatter = logging .Formatter (FORMAT )
29
+
30
+ logger = logging .getLogger (__name__ )
31
+ logger .setLevel (logging .DEBUG )
32
+
33
+ console_handler = logging .StreamHandler ()
34
+ console_handler .setFormatter (formatter )
35
+ logger .addHandler (console_handler )
36
+
37
+ file_handler = logging .FileHandler ("log.txt" )
38
+ file_handler .setFormatter (formatter )
39
+ logger .addHandler (file_handler )
40
+
41
+ words = ['debugging' , 'with' , 'default' , 'logging' , 42 ]
42
+
43
+ def process_words (words_to_process ):
44
+ for i , word in enumerate (words_to_process ):
45
+ try :
46
+ processed_word = str .capitalize (word )
47
+ logger .debug ('i=%d, processed_word=%s' , i , processed_word )
48
+ except TypeError :
49
+ logger .error ('The word is not a string' )
50
+
51
+ process_words (words )
0 commit comments