Using logging and traceback modules to log and trace exceptions in Python

logging module

The logging module is used to output the operation log. It can set different log levels and save information to the log file. Compared with print, logging can set the level of the log, control the output content in the release version, and specify the output format of the log.

  1. Using logging to output logs on the terminal
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging # Introducing logging module
# Set print log level critical > error > warning > info > debug
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s
 -%(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
# Print information to console
logging.debug(u"debugging")
logging.info(u"Perform print function")
logging.warning(u"warning")
logging.error(u"error")
logging.critical(u"Fatal error")

output

2. Use logging to output the log on the terminal and save the log to the local log file

Recommend a python learning skirt: 233 @ @ 539 @ @ 995, which has a lot of learning materials to share

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging # Introducing logging module
import os.path
# The first step is to create a logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # Log level switch
# Second, create a handler to write to the log file
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
log_name = log_path + 'log.log'
logfile = log_name
file_handler = logging.FileHandler(logfile, mode='a+')
file_handler.setLevel(logging.ERROR) # log level switch output to file
# Step 3: define the output format of handler
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
file_handler.setFormatter(formatter)
# Step 4: add the handler to the logger
logger.addHandler(file_handler)
# If you need to output on the terminal at the same time, define a streamHandler
print_handler = logging.StreamHandler() # Output to screen
print_handler.setFormatter(formatter) # Format the display on the screen
logger.addHandler(print_handler)
# log information
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
# Or using logging
logging.debug('this is a logger debug message')
logging.info('this is a logger info message')
logging.warning('this is a logger warning message')
logging.error('this is a logger error message')
logging.critical('this is a logger critical message')

Log level

FATAL: FATAL error
CRITICAL: extremely bad things, such as running out of memory and empty disk space, are rarely used
ERROR: when an ERROR occurs, such as IO operation failure or connection problem
WARNING: a very important event occurs, but it is not an error, such as a user login password error
INFO: handle daily affairs such as requests or status changes
DEBUG: use the DEBUG level during debugging, such as the intermediate state of each loop in the algorithm
traceback module

traceback is a module used to track exception information in python. It is convenient to print or save the running exception in the program for exception analysis.

Common usage

try: 
  doSomething()
except:
  traceback.print_exc()
  # logging.error(str(traceback.format_exc()))

The difference between traceback.format_exc() and traceback.print_exc():

traceback.format_exc() returns the string of exception information, which can be used to record the information in the log;
traceback.print_exc() directly prints out the exception information on the terminal;
traceback.print_exc() can also write exception information to a file. Use the following methods:

traceback.print_exc(file=open('traceback_INFO.txt','w+'))

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference value for your study or work

Published 9 original articles, praised 0, visited 5409
Private letter follow

Tags: Python

Posted on Tue, 04 Feb 2020 12:19:30 -0500 by horseatingweeds