Home >Backend Development >Python Tutorial >Best practices and tips on how to do log processing and debugging in Python
Best practices and tips on how to do log processing and debugging in Python
import logging
logger = logging.getLogger(__name__)
logger.setLevel (logging.DEBUG)
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging .DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.debug('This is a debug level log')
logger.info('This is an info level log' )
logger.warning('This is a warning level log')
logger.error('This is an error level log')
logger.critical('This is a critical level log ')
After running the above code, you will see a file named app.log
in the same directory, which contains the recorded log information. You can customize the log level, log format, and log output location as needed.
def divide(x, y):
assert y != 0, "除数不能为0" return x / y
print(divide(10, 0))
In this example , when the divisor is 0, the assertion will trigger and throw an AssertionError
exception. We can easily locate the error location based on the exception information.
import pdb; pdb.set_trace()
in the code to enter pdb debugging mode at this line of code. You can use a series of pdb commands, such as setting breakpoints, printing variable values, stepping through code, etc., to debug the program line by line. Here is an example: def add(a, b):
import pdb; pdb.set_trace() return a + b
print(add(1, 2))
When running this code , when the program is executed to import pdb; pdb.set_trace()
, it will enter the pdb debugging mode. You can enter commands to view the values of variables, step through code, and perform other debugging operations.
py debugger
(py debugger), which can provide richer debugging functions, such as remote debugging, editing code and reloading, etc. You can use pip to install the py debugger: pip install py debugger
. Reference materials:
The above is the detailed content of Best practices and tips on how to do log processing and debugging in Python. For more information, please follow other related articles on the PHP Chinese website!