Python logs require continuous learning in the continuous development. Only by constantly learning can you better master the relevant usage methods. Next we will introduce in detail how to write the relevant code. Hope to help you.
Classes implement a simple template mode, defining setup, handle, and finish to reload successors, mode Method _ init _ defines the call sequence of the three methods to ensure the operation of the three methods at the same time. Obviously, if we want to close the connection at exit, it is natural to redefine finish.
- def finish(self):
- self.request.close()
The second question is how to log. Python has the logging module logging.
- import logging
- logging.basicConfig(level=logging.DEBUG,
- format='%(asctime)s %(levelname)s %(message)s',
- filename='log.txt',
- filemode='a+')
However, we need to make a little supplement in actual use. In multi-threaded programs, to record logs, you need a unique ID related to the thread to identify something. I have not found the direct thread ID. Which brother has found it?) But Python has a built-in function named id to return the identity of an object. Note 1 ). We can get a beautiful output by predefining a template for the information to be recorded.
- def LogTemplate(self, s):
- return '[id.' + str(id(self.request)) + ']: ' + str(s)def Log(self, s):
- ss = self.LogTemplate(s)
- print ss
- logging.info(ss)
- def LogErr(self, s):
- ss = self.LogTemplate(s)
- print ss
- logging.error(ss)
Now we can write it like this.
- Def setup (self ):
- Self. Log ('enter processing thread ')
- Def finish (self ):
- Self. request. close ()
- Self. Log ("Exit Processing thread ")
In addition, the binascii module is also useful for Python logs. I will use binascii. b2a_hex is used to convert a string of binary data into visible ASCII data. It is better to use b2a_hex to convert the received data before logging.