Logging
logging
- logging has 4 different thresholds to show infomations. DEBUG, INFO, WARNING, CRITICAL.
- logging’s structure is hierchical.
root
should be in themain
. each module has its own logger, added with handler(s)(files or console).logging module itself is the root. Some setting of methods can be done. for example:
```python logger = logging.getLogger(name) #this initiates a new logger for the current module. logger.setLevel(logging.DEBUG) # set logging threshold
file_handler = logging.fileHandler(‘sample.log’) file_handler.setLevel(logging.INFO) # lift file log threshold to INFO file_handler.setFormatter(logging.Formatter()) #check attributes for Formatter in ‘https://docs.python.org/3/library/logging.html#logging.LogRecord’
stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.WARNING) # if this not set, console will use DEBUG as level set in logger. logger.addHandler(file_handler) logger.addHandler(stream_handler)
try: result = do_something() logger.INFO(‘function done’) except Error: logger.exception(‘Error happened’) #this will record the traceback in the log file and console raise Error # keeps the same error to be raised ```